내 코드는 프로세스를 분기하고 각 프로세스의 PID 및 PPID를 인쇄합니다. 자식의 PPID가 부모의 PID와 동일할 것으로 예상했지만 그대로 나타나지 않습니다.
우분투 14.04를 사용하고 있습니다.
#include <stdio.h>
#include <sys/wait.h>
int main(){
int pid;
pid = fork();
if(pid==0){
printf("\nI am the child and my parent id is %d and my id %d\n", getppid(), getpid());
}
else
printf("\nI am the parent and my pid is %d and my parent id is %d\n", getpid(), getppid());
return 0;
}
내가 얻는 결과는 다음과 같습니다.
I am the parent and my pid is 29229 and my parent id is 27087
I am the child and my parent id is 1135 and my id is 29230
답변1
내 추측은: 부모가 고아가 된 아이보다 먼저 돌아왔다는 것입니다. PID 1135는 프로세스의 새 상위가 된 사용자 초기화 프로세스여야 합니다. (Ubuntu 사용자 세션에는 2개의 하위 리퍼가 있습니다).
$ ps -ef | grep init
you 1135 ... init --user
부모가 자식을 기다리게 하려면 를 사용하세요 wait
. 실제로 다음이 include
이미 있습니다.
#include <stdio.h>
#include <sys/wait.h>
int main(){
int pid;
pid = fork();
if(pid == 0)
printf("\nI am the child and my parent id is - %d and mine id %d\n",getppid(),getpid());
else{
printf("\nI am the parent and my pid is %d and my parent id is %d\n",getpid(),getppid());
wait(NULL);
}
return 0;
}
이렇게 하면 부모가 자식의 printf
. sleep()
여기저기에 몇 가지 호출을 삽입하여 상황이 어떤 순서로 발생하는지 확인하면 이 동작을 더 명확하게 볼 수 있습니다 .
서브리퍼에 대한 자세한 내용은여기 좀 보세요.