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

Fork in shell

Can we use fork in shell script.

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

Re: Fork in shell

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:

# two hours max offline !
sleep 7200 &
echo $PID > /tmp/
wait $PID

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.

Honored Contributor
Posts: 1,015
Registered: ‎02-01-1999
Message 3 of 5 (212 Views)

Re: Fork in shell

Volker is right here..

another thing you can from the shell is


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
Posts: 17,825
Registered: ‎07-16-1998
Message 4 of 5 (212 Views)

Re: Fork in shell


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 &

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
Posts: 579
Registered: ‎09-14-2000
Message 5 of 5 (212 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:

telnet localhost smtp |&
if kill -0 $master
# find the first 200 response
while read -p line
case $line in
(2*) smtp_ready=1;;
echo could not contact smtp server
exit 1

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

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

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.