Created
May 24, 2013 18:57
-
-
Save MosheBerman/5645752 to your computer and use it in GitHub Desktop.
forkwait main
This file contains hidden or 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
main(int argc, char* argv[]) | |
{ | |
// Generate a random number between MINFORKS and MAXFORKS | |
unsigned int seed = generateSeed(0); | |
int n = rand_r(&seed) % MAXFORKS + MINFORKS; | |
// Time elapsed | |
long time = 0; | |
time = elapsedTime((int)time); | |
// Hang on to the PIDs so we can wait for them after forking | |
pid_t PIDs[n]; | |
// Fork n times | |
for (int i = 0; i < n ; i++) | |
{ | |
// Call fork() and retain the returned identifier | |
pid_t processIdentifier = fork(); | |
// Randomize the child sleep time | |
seed = generateSeed(0) % MAXPAUSE + MINPAUSE; | |
int sleeptime = rand_r(&seed); | |
// Check for errors | |
if (processIdentifier == -1) { | |
printf("Error: %i", errno); | |
} | |
// We're in the child process | |
if (!processIdentifier) | |
{ | |
// sleep for timeslept seconds | |
usleep(sleeptime); | |
exit(i); | |
} | |
else | |
{ | |
PIDs[i] = processIdentifier; | |
printf("Child %i, pid = %i, forked, waits %i usec\n", i, processIdentifier, sleeptime); | |
} | |
} | |
for (int i = 0; i < n; i++) | |
{ | |
int childid = waitpid(PIDs[i], &childid, 0); | |
printf("Child %i, pid = %i, terminated\n", childid, PIDs[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment