Main Content

Perl - multiprocess applications

Archive - Originally posted on "The Horse's Mouth" - 2006-02-13 06:07:55 - Graham Ellis

There are times that you'll be writing an application that you want to go off and perform task "x" and AT THE SAME TIME have it perform task "y", co-ordinating task "y" with task "x". Threading (NOT the subject covered here) is one possible approach. And another possible approach is forking. How does that work?

Let's say that you want to write a process that receives requests from a number of different clients and handles them sequentially - but quite slowly. A print driver would be a good example ...

1. Set up the main (to be monitoring) process, open a port, wait for requests.

2. When a request is received, note you process ID (the $$ variable), set up a pipe then fork.

The effect of the fork is to split your single process into a parent and a child each of which has copies of all your variables and each of which can continue on its own way.

You recognise that you're in the child process because the fork function returns a false value, whereas in the parent it returns the child's process ID.

The parent can then resume its wait loop, and the child can process the data.

3. When the child wants to talk to the parent, or vice versa, it can write to the pipe. A pipe opened before a fork connects any writes on the parent to reads on the child, and any writes on the child to reads on the parent.

4. If the child or parent needs to communicate with the other asyncronously (i.e. when the other is NOT waiting for an input), you use a signal. Signals are sent by the alarmingly named kill function, and collected by a sub that you've named in the %SIG hash in the receiver.

If you're writing a Perl program that forks, have a look too at the $| or autoflush special variable, and both of the select functions that are built in - one to set the default channel, and the other to check whether there's any data in your read buffers without having to wait if there isn't. Note also the use of temporary files to transfer information, and perhaps look at shared memory.

There's a simple fork example and also a more complex talker written in Perl available on our site. Training (with practicals) is available if you're attending Perl on the Web or Perl for larger projects.