C 使用管道将字符串从两个子进程发送到其父进程时出现问题
我正在尝试学习如何使用管道进行进程间通信。我的代码从主父进程创建了两个子进程,我正在尝试使用管道将字符串从两个子进程发送到父进程。第一个孩子的字符串似乎被正确发送,但第二个孩子的字符串没有被正确发送。我的计划如下:C 使用管道将字符串从两个子进程发送到其父进程时出现问题,c,C,我正在尝试学习如何使用管道进行进程间通信。我的代码从主父进程创建了两个子进程,我正在尝试使用管道将字符串从两个子进程发送到父进程。第一个孩子的字符串似乎被正确发送,但第二个孩子的字符串没有被正确发送。我的计划如下: #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int pdes0[2]; int
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pdes0[2];
int pdes1[2];
pipe(pdes0);
pipe(pdes1);
if(pdes0 < 0)
{
printf("Error creating pipe pdes0\n");
}
if(pdes1 < 0)
{
printf("Error creating pipe pdes1\n");
}
printf("Parent pid: %d\n", getpid());
for(int i=0; i<2; i++)
{
if(fork() == 0)
{
/* child */
if(i == 0)
{
/* child 0 */
printf("Child0 pid %d from parent pid %d\n", getpid(), getppid());
char child0[10] = "child0";
printf("Child0: %s\n", child0);
close(pdes0[0]);
write(pdes0[1], child0, strlen(child0)+1);
}
if(i == 1)
{
/* child 1 */
printf("Child1 pid %d from parent pid %d\n", getpid(), getppid());
char child1[10] = "child1";
printf("Child1: %s\n", child1);
close(pdes1[0]);
write(pdes1[1], child1, strlen(child1)+1);
}
exit(0);
}
else
{
/* parent */
char inbuf0[10];
char inbuf1[10];
close(pdes0[1]);
read(pdes0[0], inbuf0, 10);
printf("Parent0 read: %s\n", inbuf0);
close(pdes0[0]);
close(pdes1[1]);
read(pdes1[0], inbuf1, 10);
printf("Parent1 read: %s\n", inbuf1);
close(pdes1[0]);
}
}
wait(NULL);
}
我还不明白为什么child1的pid输出为1,因为在本例中它应该是3181。非常感谢您的帮助。提前谢谢 错误在于,无论
i
是否等于0
或1
,您都试图读取pdes0[0]
和pdes1[0]
另外,在循环的第一次运行中关闭两个描述符。当i
等于1
时,描述符不再有效,对read
的调用返回失败,您继续使用缓冲区,就像它们保存有效数据一样
下面是代码父端的更新版本
/* parent */
if ( i == 0 )
{
char inbuf0[10];
close(pdes0[1]);
read(pdes0[0], inbuf0, 10);
printf("Parent0 read: %s\n", inbuf0);
close(pdes0[0]);
}
if ( i == 1 )
{
char inbuf1[10];
close(pdes1[1]);
read(pdes1[0], inbuf1, 10);
printf("Parent1 read: %s\n", inbuf1);
close(pdes1[0]);
}
通过这种改变,我得到了预期的输出
父pid:7262
来自父pid 7262的Child0 pid 7263
Child0:Child0
Parent0改为child0
来自父pid 7262的Child1 pid 7264
Child1:Child1
家长1改为:孩子1
此外,支票
if(pdes0 < 0)
非常感谢你。这很有帮助!
if(pdes0 < 0)
if(pdes1 < 0)
int st0 = pipe(pdes0);
int st1 = pipe(pdes1);
if(st0 < 0)
{
printf("Error creating pipe pdes0\n");
}
if(st1 < 0)
{
printf("Error creating pipe pdes1\n");
}