温馨提示×

C++中怎么创建新的进程

c++
小亿
87
2024-04-02 20:37:08
栏目: 编程语言

在C++中创建新的进程有多种方法,以下是其中一种主要方法:

  1. 使用fork()exec()函数:
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid = fork();
    
    if (pid < 0) {
        std::cerr << "Failed to fork process" << std::endl;
        return 1;
    } else if (pid == 0) {
        // 子进程
        execl("/path/to/your/executable", "executable_name", NULL);
        
        // 如果exec()执行失败
        std::cerr << "Failed to execute process" << std::endl;
        return 1;
    } else {
        // 父进程
        int status;
        waitpid(pid, &status, 0);
        
        if (WIFEXITED(status)) {
            std::cout << "Child process exited with status: " << WEXITSTATUS(status) << std::endl;
        }
    }
    
    return 0;
}

在上面的示例中,首先使用fork()创建一个新的进程,然后在子进程中使用execl()函数执行另一个可执行文件。父进程会等待子进程执行完毕,并获取子进程的结束状态。如果想在子进程中执行C++代码,可以使用execl()调用自己的可执行文件路径。

0