gpt4 book ai didi

c - 管道()和 fork ()

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:00 24 4
gpt4 key购买 nike

我的程序的目标是创建两个管道和两个进程,它们相互通信以读取和写入管道。

  1. 进程 p1 从管道 c1 读取并写入管道 c2
  2. 进程 p2 从管道 c2 读取并写入管道 c1

直到从管道读取的数字小于 BIG_INT_STOP 两个进程继续增加管道中的数字。一旦这个条件为真,第一个进程读取它,关闭管道,退出并打印数字。问题是:当进程 p2 在 p1 之前结束时它工作,当进程 p1 在 p2 之前结束时它进入循环。你能解释一下为什么吗?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/wait.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#define BIG_INT_STOP 40
#define TEST_ERROR if (errno) {fprintf(stderr, \
"%s:%d: PID=%5d: Error %d (%s)\n", \
__FILE__, \
__LINE__, \
getpid(), \
errno, \
strerror(errno));}

int main(){
int c1[2], c2[2], p1, p2, z;
long a = 0, c;
pipe(c1);
pipe(c2);
write(c1[1], &a, sizeof(a));
write(c2[1], &a, sizeof(a));
p1 = fork();
p2 = fork();
switch(p1){
case -1:
TEST_ERROR;
exit(EXIT_FAILURE);
case 0:
read(c1[0], &c, sizeof(c));
while(c != BIG_INT_STOP){
++c;
write(c2[1], &c, sizeof(c));
read(c1[0], &c, sizeof(c));
}
close(c1[0]);
close(c1[1]);
close(c2[0]);
close(c2[1]);
printf("p1: %ld\n", c);
exit(0);
}
switch(p2){
case -1:
TEST_ERROR;
exit(EXIT_FAILURE);
case 0:
read(c2[0], &c, sizeof(c));
while(c != BIG_INT_STOP){
++c;
write(c1[1], &c, sizeof(c));
read(c2[0], &c, sizeof(c));
}
close(c1[0]);
close(c1[1]);
close(c2[0]);
close(c2[1]);
printf("p2: %ld\n", c);
exit(0);
}
while(wait(&z) != -1);
}

最佳答案

你的程序有点奇怪。主要问题似乎是第二个 fork 在主程序和第一个子程序中执行。事实上,您正在运行四个进程:main、main 的两个儿子和第一个儿子的儿子。这可能不是您想要的。您可能希望将第一个 switch 紧跟在第一个 fork 之后,并仅在主程序中执行第二个 fork

当然,您不会检查 readwrite 的结果值以发现意外情况。

关于c - 管道()和 fork (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47776761/

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