gpt4 book ai didi

c - 在 C 中仅在父进程上 fork 多进程

转载 作者:行者123 更新时间:2023-11-30 20:13:24 25 4
gpt4 key购买 nike

我有一个项目,其中我必须从一个父进程(即原始程序/main() 函数) fork A B C 和 D 进程。我使用管道在进程之间进行通信,并且进行了大量编码,但无法在进程之间发送正确的消息。但是,我决定回去了解 fork() 的基本概念,所以我编写了以下代码。

------编辑:我的问题是,我可以使用此模板通过管道从所有 4 个进程发送消息并从父进程读取这些消息吗?如果是这样,我必须在哪个父部分编写阅读代码?`

if (fork()) { //parent log
printf("Inside parent\n");

if (fork()) { //parent log
printf("Inside parent\n");

if (fork()) { //parent log
printf("Inside parent\n");

if (fork()) { //parent log
printf("Inside parent\n");

}else { //child process D
printf("Inside process D\n");
_exit(1);
}

}else { //child process C
printf("Inside process C\n");
_exit(1);
}

}else { //child process B
printf("Inside process B\n");
_exit(1);
}
}else { //child process A
printf("Inside process A\n");
_exit(1);
}

我的目标是从 A 到 B、从 B 到 C、从 B 到 D 发送消息,同时从任何进程(A B C 和 D)向父进程发送消息。这个代码模板正确吗?还是它的结构有问题?多谢。

最佳答案

虽然您的代码确实创建了 4 个子进程,但它可以简单得多:

int main()
{
int i;
for(i = 0; i < 4; i++) {
printf("getpid = 0x%X\n", getpid());
if(fork()) {
printf("Inside parent\n");
}
else {
printf("Inside process %c\n", 'A'+i);
exit(1);
}
}
}

关键思想是您可以通过 i 的值来区分每个子项。您甚至还可以在 switch 语句中使用 i:

int main()
{
int i;
for(i = 0; i < 4; i++) {
printf("getpid = 0x%X\n", getpid());
if(fork()) {
printf("Inside parent\n");
}
else {
switch(i) {
case 0:
printf("In process A\n");
break;
case 1:
printf("In process B\n");
break;
case 2:
printf("In process C\n");
break;
case 3:
printf("In process D\n");
break;
}
exit(1);
}
}
}

关于c - 在 C 中仅在父进程上 fork 多进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989659/

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