-
Notifications
You must be signed in to change notification settings - Fork 2
fork
flowergom edited this page Oct 27, 2015
·
1 revision
기존 프로세스가 새 프로세스를 생성하는 방법 중 하나. 이 함수는 생성한 새 프로세스를 자식 프로세스 child process라 부른다. 이 함수는 한번 호출 되나 두번 반환 된다. 자식 프로세스는 부모 프로세스(fork 를 수행한 프로세스)의 복사본이다. 예를 들어 자식은 부모의 자료구역과 힙, 스텍의 복사본을 가진다.
#include “apue.h"
int globvar = 6; /* external variable in initialized data */
char buf[] = "a write to stdout\n";
int main(void) {
int var;
pid_t pid;
/* automatic variable on the stack */
var = 88;
if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
err_sys("write error”);
printf("before fork\n”);
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) {
printf("child process\n");
globvar++;
var++;
} else {
printf("parent process\n");
sleep(2);
/* we don’t flush stdout */
/* child */
/* modify variables */
/* parent */
}
printf("pid = %ld, glob = %d, var = %d\n",(long)getpid(),globvar,var);
exit(0);
}
$ ./8.1.out
a write to stdout
before fork
parent process
child process
pid = 2596, glob = 7, var = 89 // child의 변수들은 바뀐다.
pid = 2595, glob = 6, var = 88 // parent의 변수들은 바뀌지 않는다.
fork이후에 자식이 부모보다 먼저 실행 되는지(또는 나중에 실행되는지)는 알수없고, 순서는 커널의 스케줄링 알고리즘에 따라 달라진다.