如何将posix_spawn的标准输出重定向到/dev/null

7

我有以下代码:

pid_t pid;
char *argv[] = {"execpath", NULL};
int status;
extern char **environ;    
status = posix_spawn(&pid, "execpath", NULL, NULL, argv, environ);

我该如何将子进程的STDOUT重定向到/dev/null
1个回答

11

我已经为你的示例添加了一个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示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接