I'm looking for some simple C examples showing how to create multiple
processes using the fork() command. More specifically:
a) how to create a 'chain' of 5 or so processes where a parent spawns
a child, the child spawns another child, etc. and:
b) how to create a 'fan' of 5 processes where one parent spawns 4
child processes.
Could someone point me to a thread or perhaps a web page that talks
about this, or even post some examples? I'm using the GNU C compiler
in RedHat Linux 5
Many Thanks,
Brian Losee
blo...@gte.net
Once you understand how to use fork() the above all become trivially
easy. I'd recommend you obtain a good book of Unix programming. My
current favorite is "Advanced Programming in the Unix Environment" by
W. Richard Stevens, published by Addison-Wesley. It's fifty bucks or
possibly a bit more by now, but well worth it. Mr. Stevens has an
extremely clear and accessible writing style with conveys much information
with minimum fud or obfuscation, and his examples are instructive.
But basically, to fork a child, here's a skeleton:
#include <unistd.h>
int kidpid;
int status;
kidpid = fork();
if (kidpid < 0) /* ERROR ERROR */
{
perror ("oops");
exit (0);
}
else if (kidpid == 0) /* I'm the new (child) program, do our stuff.... */
{
printf ("I'm the child, my pid is %d\n", getpid());
exit (0);
}
else /* I'm the parent. */
{
waitpid (kidpid &status, 0);
printf ("I'm the parent, my pid is: %d\nthe child's pid was %d\nwaitpid returned %d",
getpid(), kidpid, status);
exit (0);
}
If you want the child to be a different program than the parent, after the
fork succeeds, in the code for the child you should use one of the
exec() family of functions to cause the child to be replaced by the new
program you desire to run. Note that the exec'd program will have the
same PID as the forked child, since it will be a true replacement.
Fred
--
---- Fred Smith -- fre...@fcshome.stoneham.ma.us -----------------------------
The eyes of the Lord are everywhere,
keeping watch on the wicked and the good.
----------------------------- Proverbs 15:3 (niv) -----------------------------