MST

星途 面试题库

面试题:C++ 利用 posix_spawn 函数创建新进程及处理复杂参数

在 C++ 中,使用 posix_spawn 函数创建一个新进程,该新进程执行一个外部程序(假设为 /usr/bin/ls),并传递一些参数(例如 -l -a)。请详细说明 posix_spawn 函数各个参数的作用,并给出完整的代码实现,同时处理可能出现的错误。
22.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

posix_spawn 函数参数作用

int posix_spawn(pid_t *restrict pid, const char *restrict path, const posix_spawn_file_actions_t *restrict file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]);

  1. pid:指向 pid_t 类型的指针,用于返回新创建进程的进程 ID。
  2. path:指向要执行的程序路径的字符串指针,这里为 /usr/bin/ls
  3. file_actions:指向 posix_spawn_file_actions_t 类型的指针,用于指定在新进程创建前后对文件描述符进行的操作。可以为 NULL,表示不进行特殊操作。
  4. attrp:指向 posix_spawnattr_t 类型的指针,用于指定新进程的属性。可以为 NULL,表示使用默认属性。
  5. argv:一个以 NULL 结尾的字符串数组,用于传递给新进程的参数列表。第一个元素通常是程序名本身,后续元素为实际参数,如 {"ls", "-l", "-a", NULL}
  6. envp:一个以 NULL 结尾的字符串数组,用于传递给新进程的环境变量。可以为 NULL,表示使用父进程的环境变量。

代码实现

#include <iostream>
#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>

int main() {
    pid_t pid;
    char *argv[] = {"ls", "-l", "-a", NULL};
    char *envp[] = {NULL};

    int status = posix_spawn(&pid, "/usr/bin/ls", NULL, NULL, argv, envp);
    if (status != 0) {
        std::cerr << "posix_spawn error: " << status << std::endl;
        return EXIT_FAILURE;
    }

    int child_status;
    waitpid(pid, &child_status, 0);
    if (WIFEXITED(child_status)) {
        std::cout << "Child exited with status: " << WEXITSTATUS(child_status) << std::endl;
    } else if (WIFSIGNALED(child_status)) {
        std::cout << "Child terminated by signal: " << WTERMSIG(child_status) << std::endl;
    }

    return EXIT_SUCCESS;
}

错误处理

  1. posix_spawn 调用失败posix_spawn 函数返回非零值表示失败,通过 std::cerr 输出错误状态码。
  2. 等待子进程结束:使用 waitpid 等待子进程结束,并通过 WIFEXITEDWIFSIGNALED 宏检查子进程的退出状态,输出相应信息。