如何在不使用管道的情况下在父级中打印孙子的 PID?如何统计子进程和孙进程的数量?

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

编写一个C程序,使用系统调用

fork( )
创建一个子进程。从子进程,显示 PID 和 PPID 然后再次调用
fork( )
创建一个孙子并让他展示你的角色 不。从父级显示所有进程的PID和PPID,并显示总数。孩子的 processes created 还创建了孙进程的数量。演示
exit(0)
exit(1)
.

我试过这段代码

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

int main()
{
    FILE *fpPID = fopen("PIDs.txt", "w");
    fclose(fpPID);
    __pid_t child_pid = fork();

    if (child_pid < 0)
    {
        printf("Failed to create child process");
        exit(-1);
    }
    else if (child_pid == 0)
    {
        __pid_t grandChild_pid = fork();
        if (grandChild_pid < 0)
        {
            printf("Failed to create grandchild process");
            exit(-1);
        }
        else if (grandChild_pid == 0)
        {
            FILE *fpPID = fopen("PIDs.txt", "a");
            fprintf(fpPID, "%d\n", getpid());
            fclose(fpPID);

            printf("GRANDCHILD: CSM21009\n");
            exit(0);
        }
        else
        {
            printf("CHILD: PID: %d, PPID: %d \n", getpid(), getppid());
        }
    }
    else
    {
        sleep(1);
        int GrandChildPID;
        FILE *fpPID = fopen("PIDs.txt", "r");
        fscanf(fpPID, "%d", &GrandChildPID);
        fclose(fpPID);

        printf("PARENT: PID: %d, PPID: %d \n", getpid(), getppid());
        printf("PARENT: Child PID: %d, Child PPID: %d \n", child_pid, getpid());
        printf("PARENT: Grand Child PID: %d, Grand Child PPID: %d \n", GrandChildPID, child_pid);
        printf("number of Child = 1\n");
        printf("number of GrandChild = 1 \n");
        exit(0);
    }
}
c operating-system fork
1个回答
0
投票

您的代码总体上看起来不错,但是可以进行一些改进以确保子进程和孙进程正确退出并正确计算子进程和孙进程的数量。这是修改后的代码:

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

int main()
{
    int child_count = 0, grandchild_count = 0;
    pid_t child_pid = fork();

    if (child_pid < 0)
    {
        printf("Failed to create child process");
        exit(-1);
    }
    else if (child_pid == 0)
    {
        child_count++;
        printf("CHILD: PID: %d, PPID: %d\n", getpid(), getppid());
        
        pid_t grandchild_pid = fork();
        if (grandchild_pid < 0)
        {
            printf("Failed to create grandchild process");
            exit(-1);
        }
        else if (grandchild_pid == 0)
        {
            grandchild_count++;
            printf("GRANDCHILD: CSM21009\n");
            printf("GRANDCHILD: PID: %d, PPID: %d\n", getpid(), getppid());
            exit(0);
        }
        else
        {
            int status;
            waitpid(grandchild_pid, &status, 0);
            exit(0);
        }
    }
    else
    {
        int status;
        waitpid(child_pid, &status, 0);

        printf("PARENT: PID: %d, PPID: %d\n", getpid(), getppid());
        printf("
© www.soinside.com 2019 - 2024. All rights reserved.