Thursday, September 16, 2010

How to create zombie process

I know that zombie processes do not take up any system resources expect maybe in extreme cases where your system would max out the number of processes in the process table. And people usually ask "why am I seeing zombie [or <defunct>] processes" and "how do I get rid of them". I am asking just that question but I need to understand at the code level how this happens.


#!/usr/bin/perl -w
use strict;
use warnings;

use Sys::Syslog qw(:DEFAULT setlogsock);

my $keep_going = 1;

#
# startDaemon
#
my $child_pid;
if( $child_pid = fork ){
print "This is parent process and child ID is $child_pid .\n";
print "Parent process is sleep for 60 seconds ... \n";
sleep 60;
print "Parent process is exitting 0.\n";
exit 0;
}

# give the child something to do like write the /var/log/messages
setlogsock('unix');
openlog('Two', 'pid,nowait', 'local1');

my $count = 0;
while( $keep_going == 1 ) {
my $date = `date`;
chomp( $date );
syslog( "crit", "The date is [$date]" );
my $out = `date >> /tmp/Two.pl.log`;
sleep 5;
if ( $count == 2 ) { die "count is 5 ... arrgg!\n"; }
$count ++;
}
closelog();
exit (0); # child exits here


... now run it and then in another terminal execute ...


$ ps -ef | grep logg
rala 698 31230 0 15:21 pts/0 00:00:00 /usr/bin/perl -w ./logging_deamon_example3_make_zombies.pl
rala 699 698 0 15:21 pts/0 00:00:00 /usr/bin/perl -w ./logging_deamon_example3_make_zombies.pl
rala 704 32676 0 15:21 pts/1 00:00:00 grep logg
$ ps -ef | grep logg
rala 698 31230 0 15:21 pts/0 00:00:00 /usr/bin/perl -w ./logging_deamon_example3_make_zombies.pl
rala 699 698 0 15:21 pts/0 00:00:00 /usr/bin/perl -w ./logging_deamon_example3_make_zombies.pl
rala 725 32676 0 15:21 pts/1 00:00:00 grep logg
$ ps -ef | grep logg
rala 698 31230 0 15:21 pts/0 00:00:00 /usr/bin/perl -w ./logging_deamon_example3_make_zombies.pl
rala 699 698 0 15:21 pts/0 00:00:00 [logging_deamon_]
rala 727 32676 0 15:21 pts/1 00:00:00 grep logg
$ ps -ef | grep logg
rala 698 31230 0 15:21 pts/0 00:00:00 /usr/bin/perl -w ./logging_deamon_example3_make_zombies.pl
rala 699 698 0 15:21 pts/0 00:00:00 [logging_deamon_]
rala 729 32676 0 15:21 pts/1 00:00:00 grep logg


Whoo! Hoo! There a zombine!

You can keep the zombies from happening by adding ...

$SIG{'CHLD'} = 'IGNORE';

... before doing the fork.

No comments:

Post a Comment