gpt4 book ai didi

c - 意外的 pipe() 行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:59 25 4
gpt4 key购买 nike

我正在尝试让 2 个进程通过管道进行通信。我等待 child 在管道中写一个字符,然后, parent 从管道中读取字符并将其显示在屏幕上。问题是我在管道里成功写入了字符(我做了一个测试,立即从里面读取,我看到它在管道里),但是当父从管道里读取时,里面什么都没有。我真的不明白为什么;一切似乎都很好。

int PID, canal[2];
if(-1 == (PID = fork()))
{
perror("Error");
return 0;
}
if(-1 == pipe(canal))
{
perror("Error");
return 0;
}
if(PID == 0)
{
close(canal[0]);
printf("Child\n");
char buffer = 'C';
if( 0 == write(canal[1], &buffer, sizeof(char)))
printf("Didn't write anything\n");
close(canal[1]);
}
else
{
char readBuffer;
wait(NULL);
printf("Parent\n");
close(canal[1]);
if(read(canal[0], &readBuffer, sizeof(char)))
{
printf("I read: ");
printf("%c\n", readBuffer);
}
close(canal[0]);
}

最佳答案

问题是您在调用 fork 之后调用了 pipe。所以 parent 和 child 得到管道的不同副本。在调用 fork 之前将调用移至管道。

关于c - 意外的 pipe() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com