简体   繁体   中英

Printf behaviour when forking

I am trying to build a C program in which the parent creates an array of available sources and then forks some kids in order to do something. In this phase, the kids create an array using the "available" array of the parent and one more by using the array they just created.

This is my code:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
    pid_t wpid;

    int i = 0;
    int j = 0;
    int status = 0;
    int sources = 3;
    int children = 3;


    int *available = malloc(sources * sizeof(int));

    for (i = 0; i < sources; i++)
        available[i] = 20;

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

        if (pid == 0)
        {
            // kid gets here
            srand(getpid());

            printf("Kid %d created!\n", getpid());

            int *total = malloc(sources * sizeof(int));
            int *request = malloc(sources * sizeof(int));

            for (j = 0; j < sources; j++){
                total[j] = rand() % (available[j] / 2);
                printf("Kid(%d): Source(%d) = %d\n", getpid(), j, total[j]);
            }


            for (j = 0; j < sources; j++){
                request[j] = rand() % total[j];
                printf("REQUEST: Kid(%d): Source(%d) = %d\n", getpid(), j, request[j]);
            }

            printf( "==============================================================\n");


            free(total);
            free(request);

            exit(0);
        }
        // parent gets here

        sleep(1);   // readable reasons
    }

    while ((wpid = wait(&status)) > 0);

    free(available);

    return 0;
}

Problem

The problem is that sometimes when I run this program, I don't get all the prints in my terminal. For example, the second loop should print exactly 3 times REQUEST: blabla but sometimes it gets printed only twice or it doesn't gets printed at all.

What I tried

1) According to this post printf anomaly after "fork()" , "when the output of your program is going to a terminal (screen), it is line buffered". But all of my prints have a '\\n' in the end so I should not have a problem with printf's buffering.

2) Tried 'fflush(stdout)' after every print.

3) Tried to print to stderr using fprintf.

So why some prints do not appear?

The child process is exiting when total[j] is 0 , because rand() % total[j] is getting a division by zero error.

Change

request[j] = rand() % total[j];

to

request[j] = total[j] ? rand() % total[j] : -1;

This will skip the division in that case, and put -1 in request to indicate the erroneous case.

This doesn't really have anything to do with forking, except that if you had the loop in the parent process the shell would have told you that the process was crashing. Your parent process doesn't report the exit status that wait() returns, so you don't see this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM