为什么子进程和父进程的pid相同?
问题描述:
我尝试检查父进程和子进程的PID,但每当我运行该程序时,我所得到的都是它们两者的相同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;
}
答
您还没有叫getpid
或getppid
功能,你只将它们转换成整数。你需要添加括号。
printf("parent process - my pid: %d, my parent's pid: %d, my child's pid: %d\n", getpid(), getppid(), pid);
请注意,打印的错误值远远超出PID范围,即typically 32k。您的父进程正在打印正确的子PID,因为该值在交给您时是整数。