여기에서 C에서 fork() 및 exec() 시스템 호출의 효과를 볼 수 있습니다. fork는 호출 프로세스를 복제하여 새 프로세스를 생성하는 데 사용됩니다. 새 프로세스는 자식 프로세스입니다. 다음 속성을 참조하십시오.
- 하위 프로세스에는 고유한 프로세스 ID가 있습니다.
- 하위 프로세스의 상위 프로세스 ID는 호출 프로세스의 프로세스 ID와 동일합니다.
- 자식 프로세스는 부모의 메모리 잠금 및 세마포어를 상속하지 않습니다.
fork()는 자식 프로세스의 PID를 반환합니다. 값이 0이 아니면 부모 프로세스의 id이고, 0이면 자식 프로세스의 id이다.
exec() 시스템 호출은 현재 프로세스 이미지를 새 프로세스 이미지로 교체하는 데 사용됩니다. 프로그램을 현재 공간에 로드하고 진입점에서 실행합니다.
따라서 fork()와 exec()의 주요 차이점은 fork가 기본 프로세스의 복사본인 새 프로세스를 시작한다는 것입니다. exec()는 현재 프로세스 이미지를 새 이미지로 교체합니다. 부모 프로세스와 자식 프로세스가 동시에 실행됩니다.
예시
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main() {
pid_t process_id;
int return_val = 1;
int state;
process_id = fork();
if (process_id == -1) { //when process id is negative, there is an error, unable to fork
printf("can't fork, error occured\n");
exit(EXIT_FAILURE);
} else if (process_id == 0) { //the child process is created
printf("The child process is (%u)\n",getpid());
char * argv_list[] = {"ls","-lart","/home",NULL};
execv("ls",argv_list); // the execv() only return if error occured.
exit(0);
} else { //for the parent process
printf("The parent process is (%u)\n",getppid());
if (waitpid(process_id, &state, 0) > 0) { //wait untill the process change its state
if (WIFEXITED(state) && !WEXITSTATUS(state))
printf("program is executed successfully\n");
else if (WIFEXITED(state) && WEXITSTATUS(state)) {
if (WEXITSTATUS(state) == 127) {
printf("Execution failed\n");
} else
printf("program terminated with non-zero status\n");
} else
printf("program didn't terminate normally\n");
}
else {
printf("waitpid() function failed\n");
}
exit(0);
}
return 0;
} 출력
The parent process is (8627) The child process is (8756) program is executed successfully