Closed kkocdko closed 1 year ago
#include <stdio.h> #include <sys/wait.h> #include <unistd.h> int main() { setbuffer(stdout, NULL, 0); // disable the output buffer int val = 2; printf("%d", 0); int pid = fork(); if (pid == 0) { // sleep(1); val++; printf("%d", val); } else { // sleep(1); val--; printf("%d", val); wait(NULL); } val++; printf("%d", val); return 0; }
Parent first:
[main :09] > 0 [main :17] > 1 [main :18] wait until child return [child :13] > 3 [child :21] > 4 [child :22] child exit [main :21] > 2
Child first:
[main :09] > 0 [child :13] > 3 [child :21] > 4 [child :22] child exit [main :17] > 1 [main :18] wait until child return [main :21] > 2
Uncomment the sleep(1) statements to simulate each case.
sleep(1)
Parent first:
Child first:
Uncomment the
sleep(1)
statements to simulate each case.