Wait test

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
852 B
2
Indexable
Never
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <wait.h>

void calc(char process, int pid) {
    int counter = 0;
    int N = 20;

    for(int i=0; i<N; i++) {
        printf("%c process: counter = %d\t(%d)\n", process, ++counter, pid);
        fflush(stdout); // clean buffer for printf buffer
        sleep((double)rand()/(double)RAND_MAX);
    }
}

int main() {
    printf("--beginning of program \n");

    int child_status;
    pid_t pid = fork();

    if(pid == 0) {
        //child
        calc('C', (int) getpid());
    }
    else if(pid > 0) {
       //parent
        calc('P', (int) getpid());
    }
    else {
        // fork error
        printf("fork error \n");
        return(1);
    }
    printf("--end of program (%d)\n", getpid());

    wait(&child_status);

    return 0;
}