#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
intmain(intargc,char*argv[]){printf("hello world (pid:%d)\n",(int)getpid());intrc=fork();if(rc<0){fprintf(stderr,"fork failed\n");exit(1);}elseif(rc==0){printf("hello, I am child (pid:%d)\n",(int)getpid());}else{printf("hello, I am parent of %d (pid:%d)\n",rc,(int)getpid());}return0;}
fork()와 wait() 호출
wait() 시스템 콜을 호출하여 자식 프로세스 종료 시점까지 자신의 실행을 잠시 중지시킨다.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
intmain(intargc,constchar*argv[]){// insert code here...printf("hello world (pid:%d)'\n",(int)getpid());intrc=fork();if(rc<0){fprintf(stderr,"fork failen");exit(1);}elseif(rc==0){printf("hello, I am child (pid:%d)\n",(int)getpid());}else{intrc_wait=wait(NULL);printf("hello, I am parent of %d (rc_wait:%d) (pid:%d)\n",rc,rc_wait,(int)getpid());}return0;}
결과를 보면 알 수 있듯이 fork() 함수만 사용했을 때는 부모 프로세스의 정보가 먼저 출력되었지만, wait()을 사용해서 자식 프로세스의 정보가 먼저 출력 되었다.
exec() 시스템 콜
자기 자신이 아닌 다른 프로그램을 실행해야 할 때 사용한다.
fork() 시스템 콜은 자신의 복사본을 생성하여 실행한다.
exec() 시스템 콜은 자신의 복사본이 아닌 새로운 프로세스를 생성하여 실행한다.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
intmain(intargc,constchar*argv[]){printf("hello world (pid:%d)'\n",(int)getpid());intrc=fork();if(rc<0){fprintf(stderr,"fork failen");exit(1);}elseif(rc==0){printf("hello, I am child (pid:%d)\n",(int)getpid());char*myargs[3];myargs[0]=strdup("wc");myargs[1]=strdup("main.c");myargs[2]=NULL;execvp(myargs[0],myargs);printf("this shouldn't print out");}else{intrc_wait=wait(NULL);printf("hello, I am parent of %d (rc_wait:%d) (pid:%d)\n",rc,rc_wait,(int)getpid());}return0;}
결과를 보면 exec() 함수 호출 이후 “printf(“this shouldn’t print out”);” 이 출력되지 않음을 확인할 수 있다.
댓글남기기