Last active
April 14, 2019 23:01
-
-
Save twimnox/4e4d4a2fa8abe0572f364897af2477b4 to your computer and use it in GitHub Desktop.
exp1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <stdlib.h> | |
int main() { | |
int nprocesses = 3; | |
pid_t pids[32]; | |
if (getpid() != pids[0]){ | |
printf("initial process is %d\n", getpid()); | |
pids[0] = getpid(); | |
} | |
for (int i = 1; i <= nprocesses; /**/) { | |
int pid = fork(); | |
if(pid < 0){ /*unsuccessful process*/ | |
exit(EXIT_FAILURE); | |
} | |
else if (pid > 0){ /*parent process*/ | |
// store process id per creation order | |
pids[i] = pid; | |
++i; | |
// wait for all childs to finish before the parent finishes itself | |
waitpid(-1, NULL, WUNTRACED); | |
} | |
else{ /*child*/ | |
// just finish the child proc. | |
exit(EXIT_SUCCESS); | |
} | |
} | |
for (int i = 1; i <= nprocesses; ++i) { | |
// wait for each process to end before starting another | |
waitpid(pids[i], 0, 0); | |
printf("finished process %d - parent process is %d\n", pids[i], pids[i-1]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment