我有以下代码:
pid_t pid;
char *argv[] = {"execpath", NULL};
int status;
extern char **environ;
status = posix_spawn(&pid, "execpath", NULL, NULL, argv, environ);
我该如何将子进程的
STDOUT
重定向到/dev/null
?我已经为你的示例添加了一个posix_spawn_file_actions_t
,并且在我的机器上验证输出被重定向到了/dev/null。
#include <sys/types.h>
#include <stdio.h>
#include <spawn.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char ** argv) {
posix_spawn_file_actions_t action;
posix_spawn_file_actions_init(&action);
posix_spawn_file_actions_addopen (&action, STDOUT_FILENO, "/dev/null", O_WRONLY|O_APPEND, 0);
pid_t pid;
char *arg[] = {"execpath", NULL};
int status;
extern char **environ;
status = posix_spawn(&pid, "execpath", &action, NULL, argv, environ);
posix_spawn_file_actions_destroy(&action);
return 0;
}
编辑:为了完整参考,添加了MCVE示例。