Skip to content

Instantly share code, notes, and snippets.

@bigntallmike
Last active July 1, 2020 13:11
Show Gist options
  • Save bigntallmike/f8d1f3a022a5d8c11f039593ba01d0f7 to your computer and use it in GitHub Desktop.
Save bigntallmike/f8d1f3a022a5d8c11f039593ba01d0f7 to your computer and use it in GitHub Desktop.
/* The goal here is to create N forked processes and loop a list of 'jobs'
* and submit each to a free fork when it becomes free */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#define MAXCHILD 8
pid_t children[MAXCHILD];
/* Sleep random time between 500 and 1000 msec */
int takesometime()
{
int msec;
srand(getpid());
msec = rand() % 1000 + 1000;
printf("[%05d] Doing \"work\" for %d milliseconds\n", getpid(), msec);
fflush(stdout);
return usleep(msec * 1000);
}
int childbypid(int pid)
{
int child;
for (child = 0; child < MAXCHILD; child++) {
if (children[child] == pid) {
children[child] = 0;
return child;
}
}
return -1;
}
int findfreechild()
{
int child;
for (child = 0; child < MAXCHILD; child++) {
printf("Checking child %d\n", child);
fflush(stdout);
if (children[child] == 0) {
printf("Child %d is free\n", child);
fflush(stdout);
return child;
}
}
return -1;
}
void cleanchildren()
{
for (int child = 0; child < MAXCHILD; child ++) {
children[child] = 0;
}
}
int countchildren()
{
int count = 0;
for (int child = 0; child < MAXCHILD; child ++) {
if (children[child] > 0) {
count++;
}
}
return count;
}
int main(int argc, char *argv[])
{
pid_t childpid;
int event;
int events = 16;
int freeproc = -1;
int status;
cleanchildren();
/* Start children. */
for (event = 0; event < events; ++event) {
/* Get next free child or wait for one to exit */
if ((freeproc = findfreechild()) == -1) {
freeproc = childbypid(wait(&status));
}
/* Fork process */
if ((childpid = fork()) < 0) {
perror("fork");
abort();
} else if (childpid == 0) {
takesometime();
exit(0);
}
children[freeproc] = childpid;
}
/* END: Wait for children to exit. */
printf("Done jobs\n");
while (countchildren() > 0) {
childpid = wait(&status);
printf("Child with PID %d exited with status 0x%x.\n", childpid, status);
children[childbypid(childpid)] = 0;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment