void child(int pid){
printf("Child PID:%d\n",pid);
exit(0);
}
void parent(int pid){
printf("Parent PID:%d\n",pid);
exit(0);
}
void init(){
printf("Init\n");//runs before the fork
}
int main(){
init();//only runs for parent i.e. runs once
printf("pre fork()");// but this runs for both i.e. runs twice
//why???
int pid = fork();
if(pid == 0){
child(pid); //run child process
}else{
parent(pid);//run parent process
}
return 0;
}
출력 :Unix fork() 시스템 콜은 언제 실행됩니까?
Init
pre fork()Parrent PID:4788
pre fork()Child PID:0
나는 (내 경우 우분투) 유닉스 OS에서 프로세스를 가지고있다. 나는이 일이 어떻게 이루어지는 지 이해할 수 없다. fork()
함수는 두 개의 프로세스에서 내 프로그램을 분할하지만 어디에서 왔는지 알고 있습니다. 새로운 프로세스를 생성하고 전체 main 함수를 다시 실행합니까? 그렇다면 init()
은 한 번만 실행되고 printf()
은 두 번만 실행됩니다.
printf("pre fork()");
이 두 번 실행되고 init()
이 한 번만 작동하는 이유는 무엇입니까?
덕분에 많이. 정말로 도움이된다 : D – boogie666
와우, 이것은 매우 미묘하다! +1! –
개행을 넣으면 버퍼가 플러시되지 않습니다. 정규 파일로 리디렉션 된 stdout을 사용하여 코드를 실행하면 똑같은 동작이 나타납니다. stdout은 tty가 아닌 한 기본적으로 버퍼되지 않습니다. –