【问题标题】:Setting up four processes with fork() using 1 pipe使用 1 个管道使用 fork() 设置四个进程
【发布时间】:2015-12-25 04:23:34
【问题描述】:

尝试编写一个简单的程序,使用 pipe/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

【问题讨论】:

  • 有什么错误吗?它循环了多少次?这个声明的“pid”在哪里?
  • 对不起,我在那个循环上改变了太多,我把它搞砸了,它应该是 child_pid[i]。我正在编辑我得到的输出。
  • printf("Child %d: pid: %zu", i+1, child_pid[i]); 工作得很好。它只在child_pid[i] == 0 时执行,这正是它所做的(即它打印一个零)。错误在于您的概念。
  • 提示:有没有办法让进程get它自己的pid

标签: c pipe fork


【解决方案1】:

我不确定我是否正确设置了四个子进程。

对,你不应该让孩子们跳出他们的代码块,所以改变

            break;

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

如何访问父级...?

这里有getppid(),如果出于某种原因你需要的话。

我在哪里为父进程设置菜单?

main 结束之前的for 循环之后执行此操作,这就是父级继续执行的位置。

【讨论】:

    猜你喜欢
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2019-05-07
    • 2011-01-12
    相关资源
    最近更新 更多