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

标签 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

最佳答案

我已将 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 示例以供完整引用。

关于c - 如何将 posix_spawn 标准输出重定向到/dev/null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32049807/

相关文章:

c - 整数指针数组

linux - 使用 grep 命令查找包含以文件名字符开头的文本的文件

python-3.x - 将表格复制到剪贴板

c - 需要左值作为递增操作数

c - 应为 const char * 但参数是 char 类型

c++ - mbstowcs_s 函数调整大小有时会返回输入长度 + 1

c - 如何让程序停止读取代码?

linux - ubuntu apache2 日志文件权限

windows - NSClient++ 未安装在 Windows 中

linux - 对带有空列的管道分隔文件进行排序