pid_limit.c

DownloadView Raw

/**
 * pid_limit.c
 *
 * Demonstrates limiting the number of active processes via a simple counter.
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

void do_work() {
    int rand = random() % 3;
    sleep(rand);
}

int main() {

    int i = 0;
    int num_processes = 0;
    int max_processes = 4;

    while (true) {
        i++;

        if (num_processes < max_processes) {
            int wstat;
            int ret = waitpid(-1, &wstat, WNOHANG);
            if (ret > 0) {
                num_processes--;
            }
        } else {
            int wstat;
            wait(&wstat);
            num_processes--;
        }

        pid_t pid = fork();
        num_processes++;
        if (pid == 0) {
            do_work();
            exit(0);
        }
    }

    return 0;
}