Re: Fork in shell (168 Views)
Reply
Respected Contributor
Praveen Bezawada
Posts: 310
Registered: ‎09-13-2000
Message 1 of 5 (168 Views)

Fork in shell

Hi
Can we use fork in shell script.

Praveen
Honored Contributor
Volker Borowski
Posts: 1,521
Registered: ‎04-20-1998
Message 2 of 5 (168 Views)

Re: Fork in shell

Hi,
I think you can not use it directly.
Since you usally code

fork .....;
if ( ...
exec ...;

in C, I guess you like to start a process.

This can easyly done with

commandname &

Processid of this process has to be rescued from $! after the call. You can later wait for completition with wait. I use this in a delay loop for offline backups:

shut_down_application
# two hours max offline !
sleep 7200 &
PID=$!
echo $PID > /tmp/waiter.pid
wait $PID
startup_application

When backup is ok it kills the sleep and the application comes up again. When there is trouble with backup, the application starts at the end of my offline-time-window, regardless, what the backup job is doing.

Volker
Honored Contributor
Rainer von Bongartz
Posts: 1,015
Registered: ‎02-01-1999
Message 3 of 5 (168 Views)

Re: Fork in shell


Volker is right here..

another thing you can from the shell is

exec

this will replace your current shell with
and your shell is thus killed.

you might use this to startup some daemons for example


He's a real UNIX Man, sitting in his UNIX LAN making all his UNIX plans for nobody ...
Acclaimed Contributor
A. Clay Stephenson
Posts: 17,825
Registered: ‎07-16-1998
Message 4 of 5 (168 Views)

Re: Fork in shell

Hi,

Another option if you want something very much like C fork(),exec(),wait(), etc. is to use perl.

It is also very easy to add a signal handler to handle timeout issues in perl.

You should also be aware that in the shell
you can
cmd1 &
cmd2 &
cmd3 &
wait

In this case wait without an argument will
block until all the background processes have finished.

Regards, Clay
If it ain't broke, I can fix that.
Honored Contributor
Jordan Bean
Posts: 579
Registered: ‎09-14-2000
Message 5 of 5 (168 Views)

Re: Fork in shell

Shells don't have a fork command, but all external commands are forked unless exec'd.

If you want the parent to talk to the child, invoke the child as a co-process (|&) and use the -p option for read and print to talk with it. For example:

#!/usr/bin/sh
telnet localhost smtp |&
master=$!
if kill -0 $master
then
# find the first 200 response
while read -p line
do
case $line in
(2*) smtp_ready=1;;
esac
done
else
echo could not contact smtp server
exit 1
fi

if [ $smtp_ready -eq 1 ]
then
# SMTP dialog using read -p and print -p
fi

# gracefully terminate the child...
if kill -0 $master
then
print -p quit
kill $master
wait $master
fi

I pulled this out of the air, so please excuse any syntax or logical errors.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.