我想从一个父进程创建 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 并设置了 errno
到 EBADF
。那是因为你已经在循环的第一次迭代中关闭了管道的读取端,在“父”部分,在这里:
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/