Skip to content

Instantly share code, notes, and snippets.

@MosheBerman
Created May 24, 2013 21:42
Show Gist options
  • Save MosheBerman/5646703 to your computer and use it in GitHub Desktop.
Save MosheBerman/5646703 to your computer and use it in GitHub Desktop.
main(int argc, char* argv[])
{
// Wire up the timer
long time = elapsedTime(0);
/* Generate a random number between MINFORKS and MAXFORKS
*/
unsigned int seed = generateSeed(0);
int n = rand_r(&seed) % MAXFORKS + MINFORKS;
/* Log next step
*/
time = elapsedTime(1);
printf("%li: Number of forks = %i\n", time, n);
/* Hang on to the PIDs so we can wait for them after forking
*/
int *PIDs = (pid_t *)(malloc(sizeof(*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);
int minP = MINPAUSE;
int sleeptime = rand_r(&seed) % MAXPAUSE + MINPAUSE;
if (min) {
<#statements#>
}
/* Check for errors
*/
if (processIdentifier == -1) {
printf("Error: %i", errno);
}
if (!processIdentifier)
{
/* We're in the child process,
* sleep and then exit with
* i as the error code.
*/
usleep(sleeptime);
_exit(i);
}
else
{
/* We're in the parent:
* Store the PID and
* print out the results.
*/
PIDs[i] = processIdentifier;
time = elapsedTime(1);
printf("%li: Child %i, pid = %i, forked, waits %i usec\n", time, i, processIdentifier, sleeptime);
}
}
/*
* Loop through the processes and wait for them
* to terminate. Then print the childid, and the
* the pid.
*/
int status = NULL;
for (int i = 0; i < n; i++)
{
/* Wait for the child process
* and grab it's status info
*/
status = NULL;
/* Wait for the first process
* that terminates to do so.
*/
waitpid(-1, &status, 0);
int childid = -1;
if(WIFEXITED(status))
{
childid = WEXITSTATUS(status);
/* Log the results
*/
time = elapsedTime(1);
printf("%li: Child %i, pid = %i, terminated\n", time, childid, PIDs[childid]);
}
}
/* Release our PID array
*/
free(PIDs);
/* All done!
*/
time = elapsedTime(1);
printf("All done. It only took %li milliseconds!", time);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment