首页 > 解决方案 > 如何在C中获取子进程PID

问题描述

为了获得子进程的PID,我正在这样做。

pid_t pid;
pid=fork();
if(pid==0){
  //child's work
}else{
  printf("The child's PID is %d",pid);
}

我想pid从父母那里打印孩子的!那么printf pid我是否需要使用可以getpid()吗?

标签: coperating-systemforkpid

解决方案


我认为这总结了这个问题:

#include <stdio.h>
#include <unistd.h>

int main(){
    pid_t pid;
    pid = fork();
    if(pid == 0){
        printf("In child => Own pid : %d\n", getpid());
        printf("In child => Parent's pid : %d\n", getppid());
    }
    else{
      printf("In Parent => Child's pid is %d\n", pid);
      printf("In Parent => Own pid : %d\n", getpid());
    }
    return 0;   
}

推荐阅读