简体   繁体   中英

C Concurrent Processes and a Pipe

I have the following code:

for(i=0; i < argc; i++)
{
     pipe(fd[2]);
     pid=fork();

     if (pid > 0)
     {
          close(fd[1]);
          // read the string, and print it
     }
     else if (pid == 0)
     {
          close(fd[0]);
          // write the file name to the main process
          break;
     }    
}

// wait for all processes to finish

So basically, it outputs each file name in sequential order:

file1
file2
file3

But if I put printf("%d\\n", getpid()) after the for loop, the outputs seems concurrent. Some processes with a higher process id are printed first.

My question is, the way I do the pipe read/write inside the for loop, is it sequential or concurrent?

printing after the for() loop the value returned from getpid() will be printed both for the (many) child pids and the parent pid.

There is no guarantee as to what process will execute to the call to printf() first.

so the pid values can (and as you have seen) probably will) be printed in some 'random' order.

When you fork a child process, the parent and child both run concurrently. Unless they do something that synchronizes them, the order that they each run is unpredictable.

In the case of your for loop, the reads and writes in the pipes are synchronizing the processes: the parent can't return from read() until after the child has called write() . And they won't fork new children until both have done this.

But after the loop is done, there's nothing synchronizing the processes, so they'll all print their PIDs in any order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM