【问题标题】:Get child of child using fork()使用 fork() 获取孩子的孩子
【发布时间】:2018-08-10 23:51:58
【问题描述】:

我在操作系统课上遇到了一些问题。我需要在 C 中编写一个函数,其中每个孩子生成另一个孩子,每个父母只能有一个孩子。我还必须打印他们的pid。

这是我目前所拥有的:

#define MAX_COUNT 10

pid_t ex5_1 (pid_t pid) {
    pid = fork();
    if (!pid) {
        printf("ID %d Parent %d \n", getpid(), getppid());
        _exit(1);   
    }
    return pid;
}
void ex5 () {
     pid_t  pid;
     int    i;
     pid = fork();
     for (i = 1; i <= MAX_COUNT; i++) {
          pid = ex5_1(pid);
          int status;
          wait(&status);
     } 
}

如果有人能提供帮助,我将不胜感激!

【问题讨论】:

  • 你的问题是什么?
  • Idk如何生成特定数量的child的child
  • 购买“特定数量”你是说一个吗?
  • 想象 X 有一个孩子 Y,而这个 Y 有一个孩子 Z,一直持续到某个数字
  • @EugeneSh。我认为他想要一个进程链MAX_COUNT deep。

标签: c operating-system fork system-calls


【解决方案1】:

下面是这个人对 fork 的评价:

成功时,父进程返回子进程的PID,子进程返回0。失败时,在父进程中返回-1,不创建子进程,并正确设置errno。

所以你只需要像这样检查 fork 的返回:

int pid = fork();
if (pid < 0)
    // error handling here
else if (pid == 0)
    // here you are in the child
else
    // here you are in the parent

最后,要在一个孩子中创建一个孩子,你可以这样做:

void child(int i)
{
    int pid;

    printf("Child number %d, ID %d Parent %d \n", i,  getpid(), getppid());
    if (i == MAX)
        return;
    pid = fork();
    if (pid < 0)
        // error handling here
    else if (pid == 0)
        child(++i);
    else
        waitpid(pid, null, 0);
    exit(0);
}

int main() {
    int i = 0;  
    int pid = fork();
    if (pid < 0)
        // error handling here
    else if (pid == 0)
        child(++i);
    else
        waitpid(pid, null, 0);
}

【讨论】:

  • 为什么不直接做int main(void) { child(0); }
  • 同样fork()返回pid_t而不是int
  • @alk 只是为了 printf 的事情,他只想在子进程中打印,而不是在主进程中。而且我认为当它像这样分解时他会更好地理解。
  • @alk pid_t 数据类型是有符号整数类型,能够表示进程 ID。在 GNU C 库中,这是一个 int。
  • @MickaelB。非常感谢!现在我明白了方法! :-)
猜你喜欢
  • 2013-09-27
  • 1970-01-01
  • 2014-03-27
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多