3

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.

4

1 回答 1

8

使用 for 循环。每个进程都将获得它自己的循环变量副本。

int pid;
int numKids = 5;
int procNum;

for(procNum = 0; procNum < numKids; procNum++) {
    // Note: haven't included error handling...
    pid = fork();
    if (pid == 0) {
        break;
    }
}

if (pid == 0) {
    // child specific stuff. procNum is set to the "child number"
}
else {
    // parent stuff
}
于 2013-11-07T04:07:37.540 回答