gpt4 book ai didi

c - 如何在 C 中使用 "anonymous"管道进行进程同步?

转载 作者:行者123 更新时间:2023-12-04 05:35:17 24 4
gpt4 key购买 nike

我一直很难理解命令 pipe() 在 C 中是如何工作的。据我所知,匿名管道用于在两个“相关”进程之间发送/接收信息。
我发现从相应的文件描述符中读取和写入的条件非常困惑,并且不明白为什么必须关闭读取 fd 才能写入,反之亦然,以及如何依次使用它来阻止进程,直到另一个人读过或写过。

如何使用管道来同步进程?例如,如何使用 pipe() 实现以下进程层次结构?

A / B ----D\
\ C ------\
E

-A 必须在创建 B 和 C 之前完成。
-B 必须在创建 D 之前完成。
-C 和 C 必须在创建 E 之前完成。
-B 和 C 可以按任意顺序完成

非常感谢您的帮助

最佳答案

我已经模拟了您提到的流程同步并提供了评论。希望这个概念现在清楚了。

请注意,这里没有通过管道读取数据,它仅用于在管道的写入端仍然打开时通过使用读取功能的阻塞特性来实现同步。

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
#define MAXBUF 1

int main(){

int ret, i, fd[2];
char buf[MAXBUF];

//Create a Pipe
pipe(fd);

ret = fork();//Creating process A
if (0 == ret)
{
printf("Process - A created\n");
exit(0);
}
//I need to wait till Process - A completes
//Let me close my write end else I will be blocked for ever in the loop below
close(fd[1]);

//Waiting over reading the pipe -> The loop will come out when Process A exits
//Why ->since all the write ends of the pipe are closed, so read returns 0
while ((ret = read(fd[0], buf, MAXBUF)) > 0)
{
//Just Wait, the read blocks till A exits and then read returns 0
}
//Again a pipe to synchronise B and C
pipe(fd);

//Lets Create Now B and C

ret = fork();
if (0 == ret)
{
printf("Process - B created\n");
exit(0);
}
ret = fork();
if (0 == ret)
{
printf("Process - C created\n");
exit(0);

}
//Let me close my Write End of pipe
close(fd[1]);

//Here Waiting for Termination of both B and C who can terminate in any order.
while ((ret = read(fd[0], buf, MAXBUF)) > 0)
{
//This loop will turn false only if both B & C have exited.
//Since both the write ends of the pipe that
//were there in B and C will no longer be available
//after they exit and thus the read will return 0
//Just Wait ..Do nothing
}
//Now all A, B, C are finished.
//Create D and E
ret = fork();
if (0 == ret)
{
printf("Process - D created\n");
exit(0);
}
ret = fork();
if (0 == ret)
{
printf("Process - E created\n");
exit(0);

}
//Here let the main process wait for all the 5 Child to complete
//This is not needed, but I gave given so that the Shell
//Prompt is shown after the code exits..
//If this is deleted then you need to press return
//to get back the shell prompt after the code completes execution.
for (i = 0; i < 5; i++)
{
wait(NULL);
}

}

关于c - 如何在 C 中使用 "anonymous"管道进行进程同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12028566/

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