[英]C multiple processes writing to 1 pipe
嗨Linux系統(Centos 6.5)
我創建一個管道,然后嘗試派生多個子進程。 我希望子進程寫入同一分支。 (我不關心同步性)。 我發現的是,只有第一個分叉的進程才能寫入所有后續的進程,並獲得“錯誤的文件描述符”。睡眠調用僅用於調試。
樣例代碼:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <err.h>
int pipes[2];
#define FOREVER for(;;)
int main(int argc, char *argv[])
{
int rc;
int k;
int nbytes;
char buffer[4096];
rc = pipe(pipes);
if (rc <0) { perror(" Main error with pipes \n"); exit(2); }
for (k = 0; k < 10; k++)
{
rc = fork();
if (rc < 0) { perror(" Main error with pipes \n"); exit(2); }
if (rc == 0)
{
/* Child */
close(pipes[0]);
sleep(1);
sprintf(buffer,"%d",k);
printf("Buffer = ^^%s^^\n",buffer);
rc = write(pipes[1], buffer, (strlen(buffer)+1));
perror(" Write result ");
exit(0);
}
else
{
/* Parent */
close(pipes[1]);
}
}
k = 0;
sleep(2);
FOREVER
{
nbytes = read(pipes[0], buffer, sizeof(buffer));
printf(" piped %d bytes; buffer = ## %s ##k = %d\n",nbytes,buffer,k++);
}
}
結果是管道寫入:成功管道寫入:錯誤的文件描述符管道寫入:錯誤的文件描述符管道寫入:錯誤的文件描述符...
我假設您無法將2個進程寫入1個管道,但我從未在任何地方看到過這樣的內容。
謝謝
在分叉第一個孩子之后,您將關閉管道的寫入端。
移動
close(pipes[1]);
在for
循環之外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.