gpt4 book ai didi

c - 兄弟子进程之间的管道份额

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:10 25 4
gpt4 key购买 nike

在下面的代码中,我希望子 c1 block (通过管道)直到子 c2 完成(通过 pipe_close()c2)。但是它不起作用。 c1 会永远阻塞。如果我将 pipe_close() 移出 c2 并将其放入父级,它会起作用。

这是因为从父进程创建的管道不能在同级子进程之间共享吗?

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>

static void pipe_close(int *);
static void pipe_read(int *);

int
main(void)
{
int pp_main[2] = {-1, -1};
pipe(pp_main);

int ppid = getpid();
int pgid = getpgrp();

int pid_c1 = fork();
if (pid_c1 == 0)
{ // in child c1
int cpid_c1 = getpid();
int gid = getpgrp();
printf("[c1][%d][%d] is made, wait pipe ready\n", cpid_c1, gid);
pipe_read(pp_main);
printf("[c1][%d][%d] done\n", cpid_c1, gid);
}
else
{ // in parent
printf("[main][%d][%d] created child c1: %d\n", ppid, pgid, pid_c1);
int pid_c2 = fork();
if (pid_c2 == 0)
{ // in child c2
int cpid_c2 = getpid();
int gid = getpgrp();
printf("[c2][%d][%d] is made\n", cpid_c2, gid);
for (int i = 2; i > 0; --i)
{
printf("[c2][%d][%d] count down %d\n", cpid_c2, gid, i);
sleep(1);
}
pipe_close(pp_main);
printf("[c2][%d][%d] done\n", cpid_c2, gid);
}
else
{ // in parent
printf("[main][%d][%d] created child c2: %d\n", ppid, pgid, pid_c2);
}
int status;
waitpid(pid_c2, &status, 0);
}

int status;
waitpid(pid_c1, &status, 0);
return 0;
}

static void
pipe_read(int *pp)
{
char ch;
if (pp[1] >= 0)
{
close (pp[1]);
pp[1] = -1;
}
if (pp[0] >= 0)
{
while (read (pp[0], &ch, 1) == -1 && errno == EINTR);
}
}

static void
pipe_close(int *pp)
{
if (pp[0] >= 0)
close (pp[0]);
if (pp[1] >= 0)
close (pp[1]);
pp[0] = pp[1] = -1;
}

最佳答案

It works if I move pipe_close() out of c2 and put it in parent.

这是预期的行为。管道在所有 对它的引用都关闭之前不会完全关闭。在您的代码中,pipefork 之前创建。因此,父进程和子进程都打开了该管道。 c2 child 将退出,以便关闭其对管道的引用。但是,父进程阻塞等待 c1 退出。这永远不会发生,因为父进程不会显式或隐式(通过退出)关闭管道。

关于c - 兄弟子进程之间的管道份额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41754153/

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