Untitled

 avatar
unknown
plain_text
a year ago
1.2 kB
4
Indexable
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    int status;
    pid_t p1 = fork();

    if (p1 != 0) {
        // Parent process
        pid_t p2 = fork();
        if (p2 != 0) {
            waitpid(p2, &status, 0); // Wait for p2 to finish
            waitpid(p1, &status, 0); // Wait for p1 to finish
            printf("p1\n");
        } else {
            // Child process p2
            pid_t p3 = fork();
            if (p3 == 0) {
                printf("p3 ");
                exit(0);
            }
            waitpid(p3, &status, 0); // Wait for p3 to finish
            printf("p2 ");
            exit(0);
        }
    } else {
        // Child process p1
        sleep(2); // Ensure p1 runs after p2 and p3
        pid_t p5 = fork();
        if (p5 == 0) {
            printf("p6 ");
            exit(0);
        }
        waitpid(p5, &status, 0); // Wait for p6 to finish
        pid_t p4 = fork();
        if (p4 == 0) {
            printf("p5 ");
            exit(0);
        }
        waitpid(p4, &status, 0); // Wait for p5 to finish
        printf("p4 ");
        exit(0);
    }

    return 0;
}
Editor is loading...
Leave a Comment