【问题标题】:Why is pid of child process and parent process the same?为什么子进程和父进程的pid相同?
【发布时间】:2015-10-14 04:06:35
【问题描述】:

我正在尝试检查父进程和子进程的 pid,但是每当我运行程序时,我得到的是它们两个相同的 pid 值。

据我所知,getpid 获取当前进程的 pid。我错了吗? same valur of pid for both processes

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


    int main (void){

pid_t pid= fork(); 
switch (pid){ 
case -1: 
    perror("fork");
    exit(1);
        break;
case 0 :
    printf("Child Process - my pid: %d, my parent's pid: %d\n", (int)getpid, (int)getppid);
    break;
default : 
    wait();
    printf("parent process - my pid: %d, my parent's pid: %d, my child's pid: %d\n", (int)getpid, (int)getppid, (int)pid);
    break;}


    printf("End of fork\n");
    return 0;
    }

【问题讨论】:

    标签: process fork parent-child pid


    【解决方案1】:

    您还没有调用getpidgetppid 函数,您只是将它们转换为整数。您需要添加括号。

    printf("parent process - my pid: %d, my parent's pid: %d, my child's pid: %d\n", getpid(), getppid(), pid);
    

    请注意,正在打印的错误值远远超出了 PID 范围,即typically 32k。您的父进程正在打印正确的子 PID,因为该值在交给您时是一个整数。

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 2023-04-04
      • 2021-12-31
      • 2017-06-29
      • 2022-06-17
      相关资源
      最近更新 更多