내 코드는 프로세스를 분기하고 각 프로세스의 PID 및 PPID를 인쇄합니다. 자녀의 PPID가 부모의 PID와 같을 것으로 예상했지만 그렇게 나오지 않습니다.
Ubuntu 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
내 추측은 : 부모가 고아가 된 아이보다 먼저 돌아왔다. 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()
여기저기서 몇 개의 호출 을 삽입하여 어떤 순서로 발생하는지 확인하면이 동작을보다 명확하게 볼 수 있습니다.
하위 수확 자에 대한 자세한 내용은 여기를 참조하십시오 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다