c-子进程和父进程id



刚刚与子进程块中的父pid值混淆。我的程序如下:

 int main(int argc, char *argv[])
  {
    pid_t pid;
    pid=fork();
    if(pid==-1){
            perror("fork failure");
            exit(EXIT_FAILURE);
    }
    else if(pid==0){
            printf("pid in child=%d and parent=%dn",getpid(),getppid()); 
    }
    else{
            printf("pid in parent=%d and childid=%dn",getpid(),pid);
    }
    exit(EXIT_SUCCESS);
  }

输出:父项中的pid=2642,子项ID=2643

子项中的pid=2643,父项=1

在"高级Unix编程"中,它说子进程可以使用getppid()函数获得父进程id。但这里我得到的是"1",即"init"进程id。

如何获取子进程块中的父pid值。。请帮助我获取输出。

我在"Linux Mint操作系统"中执行,但在"WindRiver"操作系统中我没有遇到这个问题。这个程序会根据操作系统改变行为吗?

这是因为父亲可以/将先于儿子退出。如果一个父亲在没有请求其子代的返回值的情况下存在,则该子代将由pid=1的进程拥有。什么是在经典的UNIX或GNU系统SystemV-init。

解决方案是在父亲:中使用waitpid()

int main(int argc, char *argv[])
{
    pid_t pid;
    pid=fork();
    if(pid==-1){
        perror("fork failure");
        exit(EXIT_FAILURE);
    }
    else if(pid==0){
        printf("pid in child=%d and parent=%dn",getpid(),getppid()); 
    }
    else{
        printf("pid in parent=%d and childid=%dn",getpid(),pid);
    }
    int status = -1;
    waitpid(pid, &status, WEXITED);
    printf("The child exited with return code %dn", status);
    exit(EXIT_SUCCESS);
}

在fork之后,您有两个新进程,您可以知道父进程中的子进程id,但不能知道其他进程。如果你真的需要这个,你必须在fork之前打开一个管道(popen),然后父级可以将它写入管道,子级可以读取它

一旦父级完成执行,子级仍在运行。然后,child被称为孤儿(因为它的父级已经死亡),如果您是通过root(其pid=1)登录的,则init进程会采用它。

如果您希望子级在父级之前先退出,则使用wait()系统调用及其变体。

#include <stdio.h>
#include <unistd.h>
int main()
{
  int pid,pid2;
  pid=fork();
  if (pid<0) {
    printf("fork failed");
    exit(-1);
  } else if (pid==0) {
    printf("child id is%d",getpid());
    execlp("/bin/ls","is",NULL);
    printf("nsleeping for 2 seconds using pid of child class");
    sleep(2);
    printf("killing the child process");
    kill(getpid());
  } else {
    wait(NULL);
    printf("The parent id is %dn",getpid());
    printf("The child id is %dn",getpid());
    printf("nsleeping for 3 seconds without pid");
    sleep(3);
    printf("nchild completedn");
    exit(0);
  }
}

这很简单,因为父进程已不存在。如果您调用wait()系统函数,那么它将一直存在,直到子函数完成其工作,并且您将获得父PID。