1748244 Members
4177 Online
108760 Solutions
New Discussion юеВ

Fork in shell

 
Praveen Bezawada
Respected Contributor

Fork in shell

Hi
Can we use fork in shell script.

Praveen
4 REPLIES 4
Volker Borowski
Honored Contributor

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
Rainer von Bongartz
Honored Contributor

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 ...
A. Clay Stephenson
Acclaimed Contributor

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.
Jordan Bean
Honored Contributor

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.