C 如何显示父进程的pid

C 如何显示父进程的pid,c,unix,pid,C,Unix,Pid,首先,我要说的是,这是我关于stackoverflow的第一个问题,我对编码也很陌生,所以我提前对任何缺点表示歉意 我试图找出子进程如何显示其自己的父进程的父进程pid(子进程的祖父母pid) 这是我的代码,我添加了一条需要更改的注释: #include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main() { int pid, status, status2; pid = fork()

首先,我要说的是,这是我关于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;
    }
}
#包括
#包括
#包括
int main()
{
int pid,状态,状态2;
pid=fork();
开关(pid)
{
案例-1://在fork过程中发生错误。
printf(“Fork错误”);
打破
案例0:
pid=fork();
开关(pid)
{
案例1:
printf(“Fork错误”);
打破
案例0:
printf(“我是子进程C,我的pid是%d\n”,getpid());
printf(“我的父P有pid%d\n”,getppid());
printf(“我的祖父母G有pid%d\n”,//在这里放什么);
打破
违约:
等待(&状态);
printf(“我是父进程P,我的pid是%d\n”,getpid());
printf(“我的父G有pid%d\n”,getppid());
打破
}
打破
违约:
等待(&status2);
printf(“我是祖辈进程G,我的pid是%d\n”,getpid());
打破
}
}

此外,如果您只需将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//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
,这是否回答了您的问题?关于
%d”
什么应该是
pid\t pid
非常感谢,简单的修复,但它可以工作。我上过几堂其他语言的编码课,但这只是我第一次为C语言做的作业,而且老师的教学方法有点非传统。。。再次感谢。