Most of the examples I come across show how to fork, like this one:
main()
{
int pid;
pid = fork();
// child
if (pid == 0)
{
...
}
// Parent
else if (pID > 0)
{
...
}
}
Some show how to fork 2 children, like so
pid = fork();
// Child
if ( pid==0 )
{
...
}
// Parent
else if ( pid>0 )
{
pid=fork();
// Second child
if ( pid==0 ){
...
}
}
And here is my attempt to fork 5 children...
pid = fork();
// Child
if ( pid==0 )
{
...
}
// Parent
else if ( pid>0 )
{
pid=fork();
// Second child
if ( pid==0 ){
...
}
// Parent
else if ( pid>0 )
{
pid=fork();
// Third child
if ( pid==0 ){
...
}
// Parent
else if ( pid>0 )
{
pid=fork();
// Fourth child
if ( pid==0 ){
...
}
// Parent
else if ( pid>0 )
{
pid=fork();
// Fifth child
if ( pid==0 ){
...
}
}
}
}
}
Question:
My point is that this is insanity. Is there a cleaner way to loop through and create a varying number of children (ie. specified via a command line argument)?
NOTE: It is vitally important that the children distinguish themselves apart (ie. write "hi, I am child number 6"...) as my job involves each process signalling a different computer. Currently I am doing so using semaphores and an array of target computers. What I would rather want is increasing indeces 1..N for the processes.