gpt4 book ai didi

c - 使用 1 个管道通过 fork() 设置四个进程

转载 作者:行者123 更新时间:2023-11-30 17:10:33 24 4
gpt4 key购买 nike

尝试编写一个简单的程序,使用管道/ fork 来创建/管理 1 个父进程和 4 个子进程。父进程应该显示这样的主菜单。

Main Menu:
1. Display children states
2. Kill a child
3. Signal a child
4. Reap a child
5. Kill and reap all children

我现在编写的代码应该创建 4 个子进程。我不确定我是否正确设置了四个子进程。我知道 fork 将 0 返回给子级,将 PID 返回给父级。如何访问父级以获取这些 PID 值?我到底在哪里设置父进程的菜单?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

#define BUFSIZE 1024
#define KIDS 4
main()
{
//create unnamed pipe
int fd[2];
char buf[BUFSIZE];

if (pipe(fd) < 0)
{
perror("pipe failed");
exit (1);
}

//array of child pids
size_t child_pid[4];

//create 4 proccesses
int i = 0;
for (i = 0; i < KIDS; i++) {
child_pid[i] = fork();
if (child_pid[i]) {
continue;
} else if (child_pid[i] == 0) {
close(fd[0]);
printf("Child %d: pid: %zu", i+1, child_pid[i]);
break;
} else {
printf("fork error\n");
exit(1);
}

}

}

我的输出是:

Child 1: pid: 0
Child 2: pid: 0
Child 3: pid: 0
Child 4: pid: 0

最佳答案

I'm unsure if I'm setting up the four child processes correctly.

对,你不应该让 children 突破他们的代码块,所以改变

            break;

            sleep(99);  // or whatever you want the child to do
exit(0);

How do I access the parent …?

getppid() ,如果出于某种原因您需要它。

Where exactly do I set up the menu for the parent process?

for 循环之后、main 结束之前执行此操作,这是父级继续执行的地方。

关于c - 使用 1 个管道通过 fork() 设置四个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814315/

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