
내 코드는 프로세스를 분기하고 각 프로세스의 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()
이 동작을 더 명확하게 볼 수 있습니다 .
수확기에 대한 자세한 내용은이봐.