如何显示父进程的pid

How to display the pid of a parent process

先说一下,这是我在Whosebug上的第一个问题,我对编码也很陌生,所以如果有任何不足,我会提前表示感谢。

我正在尝试找出子进程如何显示其父进程的父 pid(子进程的祖父 pid)

这是我的代码,我添加了一条我需要更改的注释:

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

int main()
{
int pid, status, status2;
pid = fork();
switch (pid)
{
    case -1: // An error has occured during the fork process.
        printf("Fork error.");
        break;
    case 0:
        pid = fork();
        switch (pid)
        {
            case -1:
                printf("Fork error.");
                break;
            case 0:
                printf("I am the child process C and my pid is %d\n", getpid());
                printf("My parent P has pid %d\n", getppid());
                printf("My Grandparent G has pid %d\n", //what to put here );
                break;
            default:
                wait(&status);
                printf("I am the parent process P and my pid is %d\n", getpid());
                printf("My parent G has pid %d\n", getppid());
                break;
        }
        break;
    default:
        wait(&status2);
        printf("I am the Grandparent process G and my pid is %d\n", getpid());
        break;
    }
}

此外,我们将不胜感激一般提示

您可以将 pid 保存在 grandparent 中。

int pid, status, status2;
int pppid = getpid();
pid = fork();
switch (pid) {
   ....
   printf("My parent G has pid %d\n", pppid);
}

或者将getppid()的pid保存在parent中。没有获取“parent pid of parent pid”的“标准”方式,因此它与获取任何其他进程的 pid 相同。您可以检查 /proc/<pid>/stat,以及一些东西:

pid_t getppid_of_pid(pid_t pid) {
    intmax_t ret = -1;

    char *buf;
    int r = asprintf(&buf, "/proc/%jd/stat", (intmax_t)pid);
    if (r == -1) goto asprintf_err;

    FILE *f = fopen(buf, "r");
    if (f == NULL) return fopen_err;

    if (fscanf(f, "%*s %*s %*s %jd", &ret) != 1) return fscanf_err;
    
fscanf_err:
    fclose(f);
fopen_err:
    free(buf);
asprintf_err:
    return ret;
}
     

...
     printf("My Grandparent G has pid %jd\n", (intmax_t)getppid_of_pid(getppid()));

有关 /proc/../stat 中字段的说明,请参阅 man procfs