I'm trying to make a basic multiprocessing task and this is what I have. First of all, I don't know the right way to make this program as a non-blocking process, because when I am waiting for the response of a child (with waitpid
) the other processes also have to wait in the queue, but, what will happen if some child processes die before (I mean, the processes die in disorder)? So, I've been searching and I foud that I can get the PID of the process that just die, for that I use waitpid(-1, WNOHANG)
. I always get a warning that WNOHANG
is not a number, but when I added the lib sys_wait_h, I didn't get that error but the script never waits for PID, what may be the error?
#!/usr/bin/perl #use POSIX ":sys_wait_h"; #if I use this library, I dont get the error, but it wont wait for the return of the child use warnings; main(@ARGV); sub main{ my $num = 3; for(1..$num){ my $pid = fork(); if ($pid) { print "Im going to wait (Im the parent); my child is: $pid\n"; push(@childs, $pid); } elsif ($pid == 0) { my $slp = 5 * $_; print "$_ : Im going to execute my code (Im a child) and Im going to wait like $slp seconds\n"; sleep $slp; print "$_ : I finished my sleep\n"; exit(0); } else { die "couldn’t fork: $!\n"; } } foreach (@childs) { print "Im waiting for: $_\n"; my $ret = waitpid(-1, WNOHANG); #waitpid($_, 0); print "Ive just finish waiting for: $_; the return: $ret \n"; } }
Thanks in advance, bye!