Home > Net >  Unexpected output when using fork() and system() in C
Unexpected output when using fork() and system() in C

Time:11-16

I am trying to use fork() and system() to execute another C program in a child process but got some unexpected outputs. Please check my code below:

main:

int main(void)
{
    pid_t pid = fork(); 
    if (pid == 0)
    {
        std::cout<<"child started"<<std::endl;
        system("./helloworld");
        std::cout<<"child terminated"<<std::endl;
    }
    else if (pid < 0)
    {
        std::cout << "Fork failed." << std::endl;
        exit(1);
    }
    else
    {
        std::cout<<"parent started"<<std::endl;
        std::cout<<"parent terminated"<<std::endl;
    }
    return 0;
} 

helloworld.cpp:

int main(void)
{
    std::cout<<"hello world!"<<std::endl;
    return 0;
}

main program output:

ece:~/cpp> ./Pipetest
parent started
parent terminated
child started
ece:~/cpp> hello world!
child terminated
(blinking cursor here)

helloworld program output:

ece:~/cpp> ./helloworld
hello world!
ece:~/cpp> (blinking cursor here)

As is shown above, when the main program is executed, the next command-prompt (in my case, it's ece:~/cpp>) does not show up, and the program seems to be waiting for my input at the blinking cursor. In fact, the next prompt shows up only after I enter something.

I wish the main program could terminate quitely with the next command-prompt showing up, just as the helloworld program does. How could I do that?

CodePudding user response:

The shell is going to print the prompt as soon as the parent exits. If you don't want the child to print things after that, then you need to make sure the parent doesn't exit before the child does. You can do that by putting #include <sys/wait.h> at the beginning of your source file and wait(NULL); right before std::cout<<"parent terminated"<<std::endl;.

CodePudding user response:

The output is good. The output ece:~/cpp>, that you are expecting happened already is in the middle, right after the parent program exited, and the standard input is unlocked back to the console. The child is still alive and continues output to the standard output.

The similar behavior you can achieve if you run the program with the detached standard input.

ece:~/cpp> ./helloworld &
ece:~/cpp> hello world!
  • Related