Why does my fork() doesn't fork a child and output the print statements?Why use apparently meaningless do-while and if-else statements in macros?Why doesn't “cd” work in a shell script?Improve INSERT-per-second performance of SQLite?open() in Python does not create a file if it doesn't existWhy does the C preprocessor interpret the word “linux” as the constant “1”?fork and wait process does not work with mke2fs when I redirect outputwhy does fork() return all possible outputs in this combination?Why forked childern processes don't output to terminal?Why the address of the pointer variable printed differently between two printf statements without any modification to the variable?Printing behavior using fork() and write() in C

Are modern clipless shoes and pedals that much better than toe clips and straps?

If all stars rotate, why was there a theory developed that requires non-rotating stars?

Command in bash shell script to find path to that script?

How do I get toddlers to stop asking for food every hour?

What to say to a student who has failed?

How do I get a decreased-by-one x in a foreach loop?

What is this symbol: semicircles facing each other?

Would it be possible to have a GMO that produces chocolate?

Dealing with an extrovert co-worker

Did a flight controller ever answer Flight with a no-go?

Is gzip atomic?

Can a Rogue PC teach an NPC to perform Sneak Attack?

Non-visual Computers - thoughts?

“T” in subscript in formulas

Justifying the use of directed energy weapons

SQL Server Management Studio - Why is Dark Theme Disabled by Default?

How to prevent clipped screen edges on my TV, HDMI-connected?

Why isn't "I've" a proper response?

Is “I am getting married with my sister” ambiguous?

Do they have Supervillain(s)?

How to determine car loan length as a function of how long I plan to keep a car

Thank God it's Friday, tomorrow is THE weekend. Why the definite article?

Was there ever a treaty between 2 entities with significantly different translations to the detriment of one party?

How do I request a longer than normal leave of absence period for my wedding?



Why does my fork() doesn't fork a child and output the print statements?


Why use apparently meaningless do-while and if-else statements in macros?Why doesn't “cd” work in a shell script?Improve INSERT-per-second performance of SQLite?open() in Python does not create a file if it doesn't existWhy does the C preprocessor interpret the word “linux” as the constant “1”?fork and wait process does not work with mke2fs when I redirect outputwhy does fork() return all possible outputs in this combination?Why forked childern processes don't output to terminal?Why the address of the pointer variable printed differently between two printf statements without any modification to the variable?Printing behavior using fork() and write() in C






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am writing a c program in Ubuntu, and in the code I am using fork() to generate 5 different children. But, when i compile and run my program, no children are created, and the printf("Test") that I put inside the three if statements (for case fork() == 0, > 0, < 0), only in > 0, there in the output of the printf statements.



Actually a while ago, the fork() runs just fine, but after I continue my work on the program, it suddenly does not work.



Why is this happening and how should I fix it?



for (i = 0; i < proc; ++i)
printf("In for %d",i);
// TODO
int fork_result = fork();
if (fork_result == 0) // Create child process
child_pids[i] = getpid();
printf("Test 5");
printf("In if %d",i);
break;

else if(fork_result < 0)
printf("Fork failed");

else if (fork_result > 0)
printf("Parent");




Well, the expected outcome is that it would contain "Test 5" or "In if"



Actual output:



In for 0In for 1In for 2In for 3In for 4


Which the actual output does not contain any "Test 5"










share|improve this question





















  • 4





    End your printing statements with a newline; it maximizes the chance that the printed information will appear. Consider using fflush(stdout) liberally. But newlines are key: printf("Test 5n"): etc. (When debugging such code, consider printing the PID of each process in each output: printf("%d: Test 5n", (int)getpid());.) . Also think about whether break; is appropriate or whether exit(EXIT_SUCCESS); would be better.

    – Jonathan Leffler
    Mar 27 at 17:42












  • I am unable to reproduce your problem. Your code runs for me and prints Test 5 the correct number of times.

    – larsks
    Mar 27 at 17:45











  • We need enough code to replicate the problem. Your code only shows the child buffering some output. If later code doesn't actually flush it, then of course it won't show up.

    – David Schwartz
    Mar 27 at 18:11

















0















I am writing a c program in Ubuntu, and in the code I am using fork() to generate 5 different children. But, when i compile and run my program, no children are created, and the printf("Test") that I put inside the three if statements (for case fork() == 0, > 0, < 0), only in > 0, there in the output of the printf statements.



Actually a while ago, the fork() runs just fine, but after I continue my work on the program, it suddenly does not work.



Why is this happening and how should I fix it?



for (i = 0; i < proc; ++i)
printf("In for %d",i);
// TODO
int fork_result = fork();
if (fork_result == 0) // Create child process
child_pids[i] = getpid();
printf("Test 5");
printf("In if %d",i);
break;

else if(fork_result < 0)
printf("Fork failed");

else if (fork_result > 0)
printf("Parent");




Well, the expected outcome is that it would contain "Test 5" or "In if"



Actual output:



In for 0In for 1In for 2In for 3In for 4


Which the actual output does not contain any "Test 5"










share|improve this question





















  • 4





    End your printing statements with a newline; it maximizes the chance that the printed information will appear. Consider using fflush(stdout) liberally. But newlines are key: printf("Test 5n"): etc. (When debugging such code, consider printing the PID of each process in each output: printf("%d: Test 5n", (int)getpid());.) . Also think about whether break; is appropriate or whether exit(EXIT_SUCCESS); would be better.

    – Jonathan Leffler
    Mar 27 at 17:42












  • I am unable to reproduce your problem. Your code runs for me and prints Test 5 the correct number of times.

    – larsks
    Mar 27 at 17:45











  • We need enough code to replicate the problem. Your code only shows the child buffering some output. If later code doesn't actually flush it, then of course it won't show up.

    – David Schwartz
    Mar 27 at 18:11













0












0








0








I am writing a c program in Ubuntu, and in the code I am using fork() to generate 5 different children. But, when i compile and run my program, no children are created, and the printf("Test") that I put inside the three if statements (for case fork() == 0, > 0, < 0), only in > 0, there in the output of the printf statements.



Actually a while ago, the fork() runs just fine, but after I continue my work on the program, it suddenly does not work.



Why is this happening and how should I fix it?



for (i = 0; i < proc; ++i)
printf("In for %d",i);
// TODO
int fork_result = fork();
if (fork_result == 0) // Create child process
child_pids[i] = getpid();
printf("Test 5");
printf("In if %d",i);
break;

else if(fork_result < 0)
printf("Fork failed");

else if (fork_result > 0)
printf("Parent");




Well, the expected outcome is that it would contain "Test 5" or "In if"



Actual output:



In for 0In for 1In for 2In for 3In for 4


Which the actual output does not contain any "Test 5"










share|improve this question
















I am writing a c program in Ubuntu, and in the code I am using fork() to generate 5 different children. But, when i compile and run my program, no children are created, and the printf("Test") that I put inside the three if statements (for case fork() == 0, > 0, < 0), only in > 0, there in the output of the printf statements.



Actually a while ago, the fork() runs just fine, but after I continue my work on the program, it suddenly does not work.



Why is this happening and how should I fix it?



for (i = 0; i < proc; ++i)
printf("In for %d",i);
// TODO
int fork_result = fork();
if (fork_result == 0) // Create child process
child_pids[i] = getpid();
printf("Test 5");
printf("In if %d",i);
break;

else if(fork_result < 0)
printf("Fork failed");

else if (fork_result > 0)
printf("Parent");




Well, the expected outcome is that it would contain "Test 5" or "In if"



Actual output:



In for 0In for 1In for 2In for 3In for 4


Which the actual output does not contain any "Test 5"







c linux fork






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 17:47









Jonathan Leffler

591k97 gold badges709 silver badges1065 bronze badges




591k97 gold badges709 silver badges1065 bronze badges










asked Mar 27 at 17:37









Just A Bad ProgrammerJust A Bad Programmer

436 bronze badges




436 bronze badges










  • 4





    End your printing statements with a newline; it maximizes the chance that the printed information will appear. Consider using fflush(stdout) liberally. But newlines are key: printf("Test 5n"): etc. (When debugging such code, consider printing the PID of each process in each output: printf("%d: Test 5n", (int)getpid());.) . Also think about whether break; is appropriate or whether exit(EXIT_SUCCESS); would be better.

    – Jonathan Leffler
    Mar 27 at 17:42












  • I am unable to reproduce your problem. Your code runs for me and prints Test 5 the correct number of times.

    – larsks
    Mar 27 at 17:45











  • We need enough code to replicate the problem. Your code only shows the child buffering some output. If later code doesn't actually flush it, then of course it won't show up.

    – David Schwartz
    Mar 27 at 18:11












  • 4





    End your printing statements with a newline; it maximizes the chance that the printed information will appear. Consider using fflush(stdout) liberally. But newlines are key: printf("Test 5n"): etc. (When debugging such code, consider printing the PID of each process in each output: printf("%d: Test 5n", (int)getpid());.) . Also think about whether break; is appropriate or whether exit(EXIT_SUCCESS); would be better.

    – Jonathan Leffler
    Mar 27 at 17:42












  • I am unable to reproduce your problem. Your code runs for me and prints Test 5 the correct number of times.

    – larsks
    Mar 27 at 17:45











  • We need enough code to replicate the problem. Your code only shows the child buffering some output. If later code doesn't actually flush it, then of course it won't show up.

    – David Schwartz
    Mar 27 at 18:11







4




4





End your printing statements with a newline; it maximizes the chance that the printed information will appear. Consider using fflush(stdout) liberally. But newlines are key: printf("Test 5n"): etc. (When debugging such code, consider printing the PID of each process in each output: printf("%d: Test 5n", (int)getpid());.) . Also think about whether break; is appropriate or whether exit(EXIT_SUCCESS); would be better.

– Jonathan Leffler
Mar 27 at 17:42






End your printing statements with a newline; it maximizes the chance that the printed information will appear. Consider using fflush(stdout) liberally. But newlines are key: printf("Test 5n"): etc. (When debugging such code, consider printing the PID of each process in each output: printf("%d: Test 5n", (int)getpid());.) . Also think about whether break; is appropriate or whether exit(EXIT_SUCCESS); would be better.

– Jonathan Leffler
Mar 27 at 17:42














I am unable to reproduce your problem. Your code runs for me and prints Test 5 the correct number of times.

– larsks
Mar 27 at 17:45





I am unable to reproduce your problem. Your code runs for me and prints Test 5 the correct number of times.

– larsks
Mar 27 at 17:45













We need enough code to replicate the problem. Your code only shows the child buffering some output. If later code doesn't actually flush it, then of course it won't show up.

– David Schwartz
Mar 27 at 18:11





We need enough code to replicate the problem. Your code only shows the child buffering some output. If later code doesn't actually flush it, then of course it won't show up.

– David Schwartz
Mar 27 at 18:11












1 Answer
1






active

oldest

votes


















1















The child process continues to execute the code of the caller. The caller is most likely not expecting to execute the parent and all the children. You should exit the child before that happens:



for (i = 0; i < proc; ++i)
printf("In for %d",i);
fflush(stdout); // <--- here
// TODO
int fork_result = fork();
if (fork_result == 0) // Create child process
child_pids[i] = getpid();
printf("Test 5");
printf("In if %d",i);
exit(0); // <---- must have this
break;

else if(fork_result < 0)
printf("Fork failed");

else if (fork_result > 0)
printf("Parent");


// without the exit above the child will execute this code:
Some code


You must flush stdout, otherwise the children and the parent share the same prefix text in buffer, and both wil print the same prefix, when it finally flushes it. Eventually this sharing will confuse anybody trying to analyze the output.



Note: once there is an exit call, stdout will be flushed correctly.



Also, note that the different printouts might be interleaved. Putting them on different lines, with a distinguishing prefix (like i and/or pid) can help debugging.



Look at this run example






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383409%2fwhy-does-my-fork-doesnt-fork-a-child-and-output-the-print-statements%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1















    The child process continues to execute the code of the caller. The caller is most likely not expecting to execute the parent and all the children. You should exit the child before that happens:



    for (i = 0; i < proc; ++i)
    printf("In for %d",i);
    fflush(stdout); // <--- here
    // TODO
    int fork_result = fork();
    if (fork_result == 0) // Create child process
    child_pids[i] = getpid();
    printf("Test 5");
    printf("In if %d",i);
    exit(0); // <---- must have this
    break;

    else if(fork_result < 0)
    printf("Fork failed");

    else if (fork_result > 0)
    printf("Parent");


    // without the exit above the child will execute this code:
    Some code


    You must flush stdout, otherwise the children and the parent share the same prefix text in buffer, and both wil print the same prefix, when it finally flushes it. Eventually this sharing will confuse anybody trying to analyze the output.



    Note: once there is an exit call, stdout will be flushed correctly.



    Also, note that the different printouts might be interleaved. Putting them on different lines, with a distinguishing prefix (like i and/or pid) can help debugging.



    Look at this run example






    share|improve this answer































      1















      The child process continues to execute the code of the caller. The caller is most likely not expecting to execute the parent and all the children. You should exit the child before that happens:



      for (i = 0; i < proc; ++i)
      printf("In for %d",i);
      fflush(stdout); // <--- here
      // TODO
      int fork_result = fork();
      if (fork_result == 0) // Create child process
      child_pids[i] = getpid();
      printf("Test 5");
      printf("In if %d",i);
      exit(0); // <---- must have this
      break;

      else if(fork_result < 0)
      printf("Fork failed");

      else if (fork_result > 0)
      printf("Parent");


      // without the exit above the child will execute this code:
      Some code


      You must flush stdout, otherwise the children and the parent share the same prefix text in buffer, and both wil print the same prefix, when it finally flushes it. Eventually this sharing will confuse anybody trying to analyze the output.



      Note: once there is an exit call, stdout will be flushed correctly.



      Also, note that the different printouts might be interleaved. Putting them on different lines, with a distinguishing prefix (like i and/or pid) can help debugging.



      Look at this run example






      share|improve this answer





























        1














        1










        1









        The child process continues to execute the code of the caller. The caller is most likely not expecting to execute the parent and all the children. You should exit the child before that happens:



        for (i = 0; i < proc; ++i)
        printf("In for %d",i);
        fflush(stdout); // <--- here
        // TODO
        int fork_result = fork();
        if (fork_result == 0) // Create child process
        child_pids[i] = getpid();
        printf("Test 5");
        printf("In if %d",i);
        exit(0); // <---- must have this
        break;

        else if(fork_result < 0)
        printf("Fork failed");

        else if (fork_result > 0)
        printf("Parent");


        // without the exit above the child will execute this code:
        Some code


        You must flush stdout, otherwise the children and the parent share the same prefix text in buffer, and both wil print the same prefix, when it finally flushes it. Eventually this sharing will confuse anybody trying to analyze the output.



        Note: once there is an exit call, stdout will be flushed correctly.



        Also, note that the different printouts might be interleaved. Putting them on different lines, with a distinguishing prefix (like i and/or pid) can help debugging.



        Look at this run example






        share|improve this answer















        The child process continues to execute the code of the caller. The caller is most likely not expecting to execute the parent and all the children. You should exit the child before that happens:



        for (i = 0; i < proc; ++i)
        printf("In for %d",i);
        fflush(stdout); // <--- here
        // TODO
        int fork_result = fork();
        if (fork_result == 0) // Create child process
        child_pids[i] = getpid();
        printf("Test 5");
        printf("In if %d",i);
        exit(0); // <---- must have this
        break;

        else if(fork_result < 0)
        printf("Fork failed");

        else if (fork_result > 0)
        printf("Parent");


        // without the exit above the child will execute this code:
        Some code


        You must flush stdout, otherwise the children and the parent share the same prefix text in buffer, and both wil print the same prefix, when it finally flushes it. Eventually this sharing will confuse anybody trying to analyze the output.



        Note: once there is an exit call, stdout will be flushed correctly.



        Also, note that the different printouts might be interleaved. Putting them on different lines, with a distinguishing prefix (like i and/or pid) can help debugging.



        Look at this run example







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 20:01

























        answered Mar 27 at 19:44









        Michael VekslerMichael Veksler

        6,2221 gold badge9 silver badges26 bronze badges




        6,2221 gold badge9 silver badges26 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383409%2fwhy-does-my-fork-doesnt-fork-a-child-and-output-the-print-statements%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript