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

如何用fork+execv实现两个程序并行执行后继续主程序?

伪Shell并行命令功能修正方案

你的代码当前的问题是仅调用了一次wait(0),它会在第一个完成的子进程(比如ls)退出后立即返回,主进程随即执行printf("continue"),此时第二个子进程(pwd)可能仍在运行,导致输出顺序不符合「两个程序并行执行后再继续主程序」的预期。

要实现需求,需要确保主进程等待所有子进程结束后再继续执行,有两种常用修改方式:

方式一:显式等待每个子进程

直接添加一次wait(0)调用,确保两个子进程都完成:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main() 
{
    char *argv_for_program_1[] = {"ls" , NULL};
    int pid_1 = fork();
    if (pid_1 == 0)
    {     
        execv("/usr/bin/ls" , argv_for_program_1);
    }
    char *argv_for_program_2[] = {"pwd" , NULL};
    int pid_2 = fork();
    if (pid_2 == 0)
    {     
        execv("/usr/bin/pwd" , argv_for_program_2);
    }
    wait(0); // 等待第一个子进程退出
    wait(0); // 等待第二个子进程退出
    printf("continue\n");  // 建议加换行,输出更规范
}

方式二:循环等待所有子进程(更通用)

如果以后需要支持更多并行命令,用循环调用wait直到没有子进程存在会更灵活:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main() 
{
    char *argv_for_program_1[] = {"ls" , NULL};
    int pid_1 = fork();
    if (pid_1 == 0)
    {     
        execv("/usr/bin/ls" , argv_for_program_1);
    }
    char *argv_for_program_2[] = {"pwd" , NULL};
    int pid_2 = fork();
    if (pid_2 == 0)
    {     
        execv("/usr/bin/pwd" , argv_for_program_2);
    }
    
    int status;
    pid_t finished_pid;
    // 循环等待,直到所有子进程都退出(wait返回-1表示没有子进程了)
    while ((finished_pid = wait(&status)) != -1) {
        // 可选:打印子进程退出信息,比如 printf("子进程 %d 已退出\n", finished_pid);
    }
    
    printf("continue\n");
}

注意:ls和pwd的输出顺序由操作系统的进程调度决定,无法强制固定,但修改后continue一定会在两者都执行完成后才输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:45:42