简体   繁体   中英

Why my fork() does not output anything?

As code , why I don't get any outputs , can anybody tell me the issue? like that I have two fork() and each will run in a child process and my parent process will not be exit, seems right, but still don't get anything output.

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    /***********************************/
    printf("--beginning of program\n");

    int counter = 0;
    pid_t pid1 = 0;
    pid_t pid2 = 0;
    while(1){  
        if(pid1 == 0)
            pid1 = fork1();
        if(pid2 == 0)
            pid2 = fork2();
    }

    printf("--end of program--\n");
    return 0;
}

/* Two fork() */
pid_t fork1(){
    pid_t pid = fork();
    if(pid ==0 )
    {
        while(1){
            sleep(1);
            fprintf(stdout," fork1 ");
        }
    }
    return pid;
}

pid_t fork2(){
    pid_t pid = fork();
    if(pid ==0 )
    {
        while(1){
            sleep(1);
            fprintf(stdout," fork1 ");
        }
    }
    return pid;
}

stdout is buffered, it will normally only be flushed on a newline or if you explicitly flush it.

You can get your code to output the lines from the children processes by adding a newline in your statements:

fprintf(stdout, "fork1\n");

Or by explicitly flushing the buffer after the fprintf:

fflush(stdout);

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