gpt4 book ai didi

c - 使用 fork() 进行 4 个进程?

转载 作者:行者123 更新时间:2023-12-01 23:20:42 25 4
gpt4 key购买 nike

我们最近在我的应用操作系统设计类(class)中介绍了 fork(),但我不是很了解它。我们需要使用它在 C 文件中创建四个独立的进程,然后让其中三个进程写入命名管道,而第四个从中读取。

这是我到目前为止尝试过的代码:

// creating the named pipe
mknod("/tmp/namedpipe", S_IFIFO | 0600, 0);
int myPipe;

const char* colour;

pid_t p1, p2;

p1 = fork();
if (p1 < 0)
{
printf("Fork failed\n");
}
else if (p1 == 0) // this is the child of p1, we'll call it "red"
{
printf("\nPid %d %s", getpid(), "(red) started\n");
myPipe = open("/tmp/namedpipe", O_WRONLY);
colour = "RED\n";
write(myPipe, colour, strlen(colour) +1);
close(myPipe);
}
else // the is the parent of p1, we'll call it "green"
{
printf("\nPid %d %s", getpid(), "(red) started\n");
myPipe = open("/tmp/namedpipe", O_WRONLY);
colour = "RED\n";
write(myPipe, colour, strlen(colour) +1);
close(myPipe);

p2 = fork();
if (p2 < 0)
{
printf("Fork failed\n");
}
else if (p2 == 0) // this is the child of p2, we'll call it "blue"
{
printf("\nPid %d %s", getpid(), "(blue) started\n");
myPipe = open("/tmp/namedpipe", O_WRONLY);
colour = "BLU\n";
write(myPipe, colour, strlen(colour) +1);
close(myPipe);
}
else // the is the parent of p2, we'll call it "reader"
{
printf("This is the reader process");
myPipe = open("/tmp/namedpipe", O_RDONLY);
char nextChar;
while (read(myPipe, &nextChar, 1) == 1)
printf("%c", nextChar);
close(myPipe);
}
}

如果您注释掉所有与管道相关的语句,这段代码似乎可以正常工作,但否则它会执行前两个打印语句,然后挂起,强制执行 CTRL-C。我不确定问题是出在 fork 上,还是与我写入和读取管道的方式有关。请告诉我。

最佳答案

没有 O_NONBLOCK 的命名管道打开在进程之间同步。如果一个进程试图以写方式打开,它将阻塞直到其他进程试图以读方式打开。如果顺序颠倒,则读取进程将被阻塞,直到写入进程尝试打开。无论哪种方式,两个打开都同时成功。

在您的程序中,您创建了一个尝试打开以进行写入的子进程“red”,以及一个也尝试打开以进行写入的父进程“green”。还没有人阅读,所以两者都被屏蔽了。未到达将创建其他 2 个进程的代码,因为它在阻塞它的“绿色”进程中打开之后出现。

关于c - 使用 fork() 进行 4 个进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17870129/

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