热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C并发进程和管道-CConcurrentProcessesandaPipe

Ihavethefollowingcode:我有以下代码:for(i0;i<argc;i++){pipe(fd[2]);pidfork();

I have the following code:

我有以下代码:

for(i=0; i  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.

但是如果我在for循环之后放置printf(“%d \ n”,getpid()),输出似乎是并发的。首先打印一些具有更高进程ID的进程。

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

我的问题是,我在for循环中进行管道读/写的方式是顺序还是并发?

2 个解决方案

#1


1  

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

在for()循环之后打印从getpid()返回的值将被打印为(多个)子pid和父pid。

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

无法保证首先对printf()的调用执行什么进程。

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

所以pid值可以(并且如你所见)可能会以某种“随机”顺序打印。

#2


1  

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.

在for循环的情况下,管道中的读取和写入正在同步进程:在子进程调用write()之后,父进程无法从read()返回。并且他们不会分娩新孩子,直到他们都这样做。

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

但是在循环完成之后,没有任何东西可以同步进程,所以它们都会以任何顺序打印它们的PID。


推荐阅读
author-avatar
BigUncle
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有