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

时间:2015-08-17 11:59:05

标签: c linux

我有以下代码:

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 个答案:

答案 0 :(得分:4)

我在您的示例中添加了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_RDONLY, 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样本以供完整参考。