You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用fork()与system()时出现意外输出及命令提示符异常问题

问题根因
  • 输出乱序、提示符看起来未正常显示的核心原因是:父进程没有等待子进程运行结束就提前退出了。
  • shell监测到前台运行的主程序(父进程)退出后,会立刻打印新的命令提示符,但此时fork出来的子进程还在继续运行,后续子进程的输出(包括helloworld的打印、child terminated日志)就会输出到已经打印好的提示符后面,就出现了你看到的ece:~/cpp> hello world!的异常效果。你以为程序在等输入,其实提示符已经打印过了,只是被后续输出顶到了前面,任意输入回车后shell会重新打印新的提示符而已。
修复方案

只需要在父进程的逻辑中添加等待子进程退出的逻辑即可,需要引入<sys/wait.h>头文件,调用wait()或者waitpid()函数阻塞父进程,直到子进程运行结束再继续执行父进程后续逻辑。

修改后的主程序代码如下:

#include <iostream>
#include <sys/types.h>
#include <sys/wait.h> // 新增wait相关头文件
#include <unistd.h>
#include <stdlib.h>

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;
        wait(NULL); // 新增:等待任意子进程退出后再执行后续逻辑
        std::cout<<"parent terminated"<<std::endl;
    }
    return 0;
}
效果验证

修改后运行程序的输出顺序会变为:

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

和单独运行helloworld的体验完全一致,命令提示符会在所有进程都退出后正常打印。

内容的提问来源于stack exchange,提问作者anjo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:36:03