【问题标题】:How to display the pid of a parent process如何显示父进程的pid
【发布时间】:2021-06-24 15:08:57
【问题描述】:

首先让我说这是我关于 stackoverflow 的第一个问题,而且我对编码也很陌生,所以我提前对任何缺点表示感谢。

我正在尝试找出子进程如何显示其父进程的父 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;
    }
}

另外,一般提示将不胜感激

【问题讨论】:

标签: c unix pid


【解决方案1】:

您可以将 pid 保存在祖父母中。

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

或将getppid() 的pid 保存在父级中。没有获取“父 pid 的父 pid”的“标准”方法,因此它与获取任何其他进程的 pid 相同。你可以检查/proc/&lt;pid&gt;/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

【讨论】:

  • 非常感谢,简单的修复,但它有效。我参加了几门其他语言的编码课程,但这只是我的第一个 C 作业,而且讲师有一些非常规的教学方法......再次感谢。
猜你喜欢
  • 1970-01-01
  • 2010-09-05
  • 2010-09-16
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 2014-12-11
  • 2014-06-25
相关资源
最近更新 更多