Untitled

 avatar
unknown
plain_text
a year ago
918 B
3
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <number_of_processes>\n", argv[0]);
        return EXIT_FAILURE;
    }

    int n = atoi(argv[1]);

    if (n <= 0) {
        fprintf(stderr, "Please provide a positive integer greater than 0.\n");
        return EXIT_FAILURE;
    }

    for (int i = 0; i < n; ++i) {
        pid_t pid = fork();

        if (pid < 0) {
            perror("fork error");
            return EXIT_FAILURE;
        } else if (pid == 0) {
            // Child process
            printf("Hello from child process %d (PID %d)\n", i + 1, getpid());
            exit(EXIT_SUCCESS);
        } else {
            // Parent process
            // Wait for the child to complete to avoid creating zombies
            wait(NULL);
        }
    }

    return EXIT_SUCCESS;
}
Leave a Comment