Gist of the Day: Playing with Forks

Parallel processing is all the rage these days, and life has me at a point where I’m needing to use it. I am having to minimize dependencies in the task at hand, so I’m having to forego my usual CPAN modules and use basic system calls. It’s not terribly complicated, but just to refresh myself on the basics I went ahead and whipped up a quick demo that I thought others might find useful. This is a very simple demonstration of how to use fork() and wait().

Setting the Stage

So our demo here does three things:

  1. Forks five children
  2. Each child sleeps for three seconds and then exits
  3. The parent waits for each child to exit before allowing itself to exit

Please note that this is using blocking waits, so your program will sit there at the wait() system call until the next child process exits. Using this system call in this program is essential, failing to do so and failing to set SIGCHLD to "IGNORE" could cause zombie processes. There are ways to use non-blocking waits, but in the program I was writing earlier today I wanted my program to wait until all of the children were done.

The Code


Here’s my output:
manchicken@vm-0:~/GitHub/gist_per_day.git$ perl ./Perl/fork_play.pl

Hi! My name is 579.
Hi! My name is 578.
Hi! My name is 577.
Hi! My name is 576.
Hi! My name is 575.
Hi! My name is 574.
I just reaped PID 578.
I just reaped PID 579.
I just reaped PID 577.
I just reaped PID 576.
I just reaped PID 575.
I just reaped PID 574.
I’m all done here.

Conclusions

So I’ve been away for a while with the move and the holidays and all, but I’m hoping to jump back into these a little bit. They may end up being a bit smaller than they used to be, but I’m hoping to get back into them a bit. Hopefully you found this useful.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.