面试题答案
一键面试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]);
pid
:指向pid_t
类型的指针,用于返回新创建进程的进程 ID。path
:指向要执行的程序路径的字符串指针,这里为/usr/bin/ls
。file_actions
:指向posix_spawn_file_actions_t
类型的指针,用于指定在新进程创建前后对文件描述符进行的操作。可以为NULL
,表示不进行特殊操作。attrp
:指向posix_spawnattr_t
类型的指针,用于指定新进程的属性。可以为NULL
,表示使用默认属性。argv
:一个以NULL
结尾的字符串数组,用于传递给新进程的参数列表。第一个元素通常是程序名本身,后续元素为实际参数,如{"ls", "-l", "-a", NULL}
。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;
}
错误处理
posix_spawn
调用失败:posix_spawn
函数返回非零值表示失败,通过std::cerr
输出错误状态码。- 等待子进程结束:使用
waitpid
等待子进程结束,并通过WIFEXITED
和WIFSIGNALED
宏检查子进程的退出状态,输出相应信息。