Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.6 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    pid_t pids[4];
    int status;

    for (int i = 0; i < 4; i++) {
        pids[i] = fork();
        if (pids[i] == 0) {
            while (1) {
                sleep(1);
            }
            exit(0);
        } else if (pids[i] < 0) {
            perror("fork failed");
            exit(EXIT_FAILURE);
        }
    }

    printf("Child processes created with PIDs:\n");
    for (int i = 0; i < 4; i++) {
        printf("Child %d: PID = %d\n", i + 1, pids[i]);
    }

    printf("Terminating Child 3 -> PID: %d\n", pids[2]);
    kill(pids[2], SIGKILL);
    pid_t term = waitpid(pids[2], &status, 0);
    printf("Child process %d terminated with signal status %d\n", term, WTERMSIG(status));

    printf("Terminating Child 2 -> PID: %d\n", pids[1]);
    kill(pids[1], SIGKILL);
    term = waitpid(pids[1], &status, 0);
    printf("Child process %d terminated with signal status %d\n", term, WTERMSIG(status));

    printf("Terminating Child 1 -> PID: %d\n", pids[0]);
    kill(pids[0], SIGKILL);
    term = waitpid(pids[0], &status, 0);
    printf("Child process %d terminated with signal status %d\n", term, WTERMSIG(status));

    printf("Terminating Child 4 -> PID: %d\n", pids[3]);
    kill(pids[3], SIGKILL);
    term = waitpid(pids[3], &status, 0);
    printf("Child process %d terminated with signal status %d\n", term, WTERMSIG(status));

    printf("Parent process with PID = %d terminating . . .\n", getpid());
    return 0;
}
Leave a Comment