int value = 5;
int main() {
pid_t pid;
pid = fork();
if (pid == 0) { // child process
value += 15;
return 0;
}
else if (pid > 0) { // parent process
wait(NULL);
printf("Parent: value = %d\n", value); // LINE A
}
}
결과
Parent: value = 5
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
/*
* How many processes are created?
*/
int main() {
fork(); // fork a child process
fork(); // fork another child process
fork(); // and fork another
return 0;
}
-> 총 8개 프로세스 생성됨
[image:A9B64F20-DB6E-4684-91C3-0135EBCA1BF5-10634-000000D353062135/IMG_7988.jpg]
#include <stdio.h>
#include <unistd.h>
/*
* How many processes are created?
*/
int main() {
int i;
for (i = 0; i < 4; i++)
fork();
return 0;
}
-> fork() 4번 실행했으므로 16개의 프로세스가 생성됨
int main() {
pid_t pid;
pid = fork();
if (pid == 0) { // child process
execlp("/bin/ls", "ls", NULL);
printf("LINE J\n");
}
else if (pid > 0) { // parent process
wait(NULL);
printf("Child Complete\n");
}
return 0;
}
-> execlp() 시스템 콜이 명령어를 완전히 덮어 쓰기 때문에 LINE J는 출력되지 않는다.
int main() {
pid_t pid, pid1;
pid = fork();
if (pid == 0) { // child process
pid1 = getpid();
printf("child: pid = %d\n", pid);
printf("child: pid1 = %d\n", pid1); // B
}
else if (pid > 0) { // parent process
pid1 = getpid();
printf("parent: pid = %d\n", pid); // C
printf("parent: pid1 = %d\n", pid1); // D
wait(NULL);
}
return 0;
}
결과
parent: pid = 3645 //자식 PID
parent: pid1 = 3644 //자신의 PID
child: pid = 0 //fork()로 리턴된 PID
child: pid1 = 3645 //자신의 PID
#define SIZE 5
int nums[SIZE] = {0, 1, 2, 3, 4};
int main() {
pid_t pid;
int i;
pid = fork();
if (pid == 0) { // child process
for (i = 0; i < SIZE; i++) {
nums[i] *= i;
printf("CHILD: %d \n", nums[i]); // LINE X
}
}
else if (pid > 0) { // parent process
wait(NULL);
for (i = 0; i < SIZE; i++) {
printf("PARENT: %d \n", nums[i]); // LINE X
}
}
return 0;
}
결과
CHILD: 0, 1, 4, 9, 16
PARENT: 0, 1, 2, 3, 4
-> 그래서 Synchronization 동기화가 필요함.
int main() {
pid_t pid = fork();
if (pid > 0) {
wait(NULL);
// LINE A
} else {
pid = fork();
if (pid == 0) {
// LINE B
} else {
wait(NULL);
// LINE C
}
}
// LINE D
}
1) B-C-A-D-D-D
2) B-C-D-A-D-D
3) B-A-D-C-D-D
4) B-D-C-D-A-D
int x = 10;
int main() {
pid_t pid = fork();
if (pid == 0) {
x += 10;
} else {
wait(NULL);
pid = fork();
x += 10;
if (pid > 0) {
wait(NULL);
} else {
x += 10;
}
}
printf(“%d “, x);
}
1) 20 20 30
2) 20 30 20
3) 20 30 30
4) 20 20 20