[comp.lang.perl] exiting child generates "zombie"

merlyn@iwarp.intel.com (Randal Schwartz) (07/13/90)

In article <1990Jul12.154824.12595@ccu.umanitoba.ca>, rahardj@ccu (B. Rahardjo) writes:
| 
| Why do I get <defunct> status if I exit from a child ?
| I included a simple program below. Run the program, but
| before pressing return please observe the child status (ps -ux)
| here is what I get :
| 
| ic4% ps -ux
| ....
| rahard   27666  0.0  0.0    0    0 ?  Z    Jul  7  0:00 <defunct>
| 
| They will disappear when the parent exits.

Cuz this is the way it works in UNIX.  The zombie process isn't really
anything more than a process-table entry (no swap space is consumed).
It has to hang around for the parent to wait for it, because there's
the exit status and PID to be concerned about.  It *does* count
towards your per-user limit though.

If you don't want a zombie, do a double fork:

...
unless (fork) { # this is the child
	unless (fork) { # this is the child's child
		some_long_operation;
		exit 0;
	}
	# first child exits
	exit 0;
}
wait; # parent reaps first child

The first child spawns a second child, and then immediately exits.
The second child becomes an orphan (ppid == 1, if you need to check),
and will be "wait"-ed on by the granddaddy process "init" (pid = 1).
The first child is wait-ed on by the original process.

There... clear as mud? :-)

print "Just another Perl hacker, and UNIX hacker to boot..."
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/