linux - 具有多个子进程的管道

标签 linux c

我想从一个父进程创建 N 个进程,这个子进程必须读取该父进程写入的内容,但我只有第一个进程读取正确:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){


pid_t pid;

int fd[2];
char buff[50];

char str[] = "Hello";

if(pipe(fd) == -1){
    fprintf(stderr, "pipe Failed");
    return 1;
}

for(int num_process = 0; num_process < 3; num_process++){
    pid = fork();
    if(pid < 0){
        perror("Error");
        exit(1);
    }

    if(pid == 0){ //child code
        printf("Child %i (pid= %i)\n", num_process, getpid());


    close(fd[1]);
    read(fd[0], buff, sizeof(buff)); //read from pipe
    printf("Read child = %s\n", buff);
    close(fd[0]);
    exit(0);
    }

    else{//parent
        printf("Im parent %i\n",getpid());
        close(fd[0]);
        write(fd[1], str,strlen(str)+1);
        printf("Parent send %s\n", str);
        close(fd[1]);
        for(int num_process = 0; num_process < 3; num_process++){
        wait(NULL);
        }
    }
}

return 0;
}

输出:

Im parent 5863
Parent send Hello
Child 0 (pid= 5864)
Read child = Hello
Im parent 5863
Parent send Hello
Child 1 (pid= 5865)
Read child = 
Im parent 5863
Parent send Hello
Child 2 (pid= 5866)
Read child = 

最佳答案

read(fd[0], buff, sizeof(buff)); //read from pipe
printf("Read child = %s\n", buff);

如果您确实检查了 read 的返回值(您总是应该这样做),您会发现它在第 2 次和第 3 次返回 -1 并设置了 errnoEBADF。那是因为你已经在循环的第一次迭代中关闭了管道的读取端,在“父”部分,在这里:

   printf("Im parent %i\n",getpid());
   close(fd[0]);

跟在后面的 write 也是一样的:

   write(fd[1], str,strlen(str)+1);
   printf("Parent send %s\n", str);
   close(fd[1]);

fd[1] 将在循环的第 1 次迭代中关闭,write 将在第 2 次和第 3 次因 EBADF 而失败时间。

关于linux - 具有多个子进程的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53646103/

相关文章:

c - 如何在我的 C 字符串前面插入单个字符?

c - NesC 中的动态数组与 Tinyos 1,x

linux - 不包含字符串的处理行和匹配行下方的输出行

linux - "Upload of file ' ... ' was successful, but error occurred while setting the permissions and/or timestamp"在 PowerShell 中使用 WinSCP .NET 程序集时

c - fork 过程的输出

c - 如何从文件中读入3个输入值并按顺序读取它们?

c - 需要有关伪代码/算法的帮助 - 链表合并

linux - nmap中的空ip地址是什么意思?

linux - 邮件被发送到本地域而不是远程域

c - 了解 memcpy() 的源代码