在 C++ 中使用 fork() 和 system() 时出现意外输出

Unexpected output when using fork() and system() in C++

我正在尝试使用 fork() 和 system() 在子进程中执行另一个 C++ 程序,但得到了一些意外的输出。请检查下面我的代码:

主要内容:

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;
}

主程序输出:

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

helloworld 程序输出:

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

如上所示,当主程序执行时,下一个命令提示符(在我的例子中是ece:~/cpp>)没有出现,程序似乎在等待我的输入在闪烁的光标处。事实上,下一个提示只有在我输入内容后才会出现。

我希望主程序可以在出现下一个命令提示符时完全终止,就像 helloworld 程序一样。我该怎么做?

输出良好。您期望的输出 ece:~/cpp> 已经在中间,就在 parent 程序退出之后,标准输入被解锁回到控制台。 child 仍然存在并继续输出到标准输出。

如果您 运行 具有分离标准输入的程序,您可以实现类似的行为。

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

shell 将在 parent 退出后立即打印提示。如果您不希望 child 在此之后打印内容,那么您需要确保 parent 不会在 child 退出之前退出。您可以通过将 #include <sys/wait.h> 放在源文件的开头并将 wait(NULL); 放在 std::cout<<"parent terminated"<<std::endl;.

之前来做到这一点