使用fork()获取孩子的孩子

问题描述 投票:1回答:1

我在操作系统课上遇到了一些麻烦。我需要在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);
     } 
}

如果有人能提供帮助,我将非常感激!

c operating-system fork system-calls
1个回答
2
投票

这是男人对叉子说的话:

成功时,子进程的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);
}
© www.soinside.com 2019 - 2024. All rights reserved.