[TriLUG] How to spawn separate process and get pid.

Brian Weaver brianweaver at nc.rr.com
Fri Jan 21 12:45:53 EST 2005


You can do it in bash using something similar to the following:

#!/bin/bash
# $@ represents all the arguments except the name of the program '$0'
#
# this executes the command in the background and kills it after 10
# minutes if it is still running.
#
$@ >/dev/null 2>&1 &
pid=$!
sleep 600
if kill -0 $pid >/dev/null 2>&1 ; then
	# still alive, but not for long
	kill -HUP $pid
	sleep 2
	if kill -0 $pid >/dev/null 2>&1 ; then
		kill -TERM $pid
		sleep 2
		if kill -0 $pid >/dev/null 2>&1 ; then 
			kill -KILL $pid # murder it!
		fi
	fi
fi
# end of script.

I don't promise the above script is error free, but you get the idea.
'$!' represents the pid of the last background process. You might want
to 'disown' the process after you have the pid too.

-Weave

Wesley Zhang [xyzhang at cisco.com] wrote on Fri, Jan 21, 2005 at 11:49:15AM -0500:
> Hi All,
> 
> I am a newbie on shell script. But I would like to use linux shell 
> script to control a job that runs forever and will be terminated after 
> 10 minute. My thought for this is following:
> 
>  pid = start-job-for ("cmd") // has to be a separate process
>  sleep 10 min
>  kill pid.
> 
> How can I spawn a separate process to execute my command and get the 
> proper process id?
> 
> Thanks,
> Wesley
> -- 
> TriLUG mailing list        : http://www.trilug.org/mailman/listinfo/trilug
> TriLUG Organizational FAQ  : http://trilug.org/faq/
> TriLUG Member Services FAQ : http://members.trilug.org/services_faq/
> TriLUG PGP Keyring         : http://trilug.org/~chrish/trilug.asc

-- 
It is by caffeine alone I set my mind in motion. It is by the juice of
the coffee bean that thoughts acquire speed, the lips acquire stains,
stains become a warning. It is by caffeine alone I set my mind in motion.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://www.trilug.org/pipermail/trilug/attachments/20050121/61010864/attachment.pgp>


More information about the TriLUG mailing list