Shell scripts - getting parent status in read

David Elliott dce at Solbourne.COM
Sun Apr 23 07:26:27 AEST 1989


I have an interesting problem.  I have a program that runs attached to
the terminal, and it runs shell scripts underneath.  The shell script
and the parent communicate via pipes, and the most common situation is
for the shell script to be executing a "read" command, waiting for the
parent to send down a response (usually as a result of the user
typing).

I have things set up such that if the shell script quits, the parent
knows this and quits, and if the parent quits gracefully, it tells the
shell script to quit as well.

The problem case is where the parent doesn't terminate gracefully, such
as when it dumps core or when I quit from under the debugger.  In this
case, the shell script just sits in read forever.

Is there a way for the shell script to detect that this has happened
and quit?  Obviously, this is out of the realm of a SIGPIPE trap, since
that means that you are writing to a pipe with no one to read it, and I
know of no SIGPARENT.

One idea I came up with was to change the read loop to something like

	checkparent()
	{
		if kill -0 "$PPID" 2>/dev/null
		then
			(sleep 30 ; kill -12 $$) &
			return
		fi
		exit 1
	}

	while
		...
		trap "checkparent" 12
		(sleep 30 ; kill -12 $$) &
		read event
		trap "" 12
	do
		...
	done

Basically, this traps for signal 12 (which is SIGSYS; I chose it
because it's not likely in this case) and fires off a process to sleep
for a while and then "spring" the trap.  The function "checkparent"
checks to see if the parent process (whose id can be passed to the
shell script) is still alive, and if not forces the shell script to
exit.  If the parent is alive, it resets the trap and returns so that
the read can complete.

Can anyone think of an easier method for checking this, or a way to
have the shell script just killed when the parent goes away?

-- 
David Elliott		dce at Solbourne.COM
			...!{boulder,nbires,sun}!stan!dce



More information about the Comp.unix.wizards mailing list