mrdvlpr
mrdvlpr

Reputation: 556

how to redirect posix_spawn stdout to /dev/null

I have the following code:

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

How can I redirect the child process STDOUT to /dev/null?

Upvotes: 7

Views: 3983

Answers (1)

implmentor
implmentor

Reputation: 1416

I've added a posix_spawn_file_actions_t to your sample and verified on my machine that the output gets redirected to /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;
}

EDIT: Added MCVE sample for complete reference.

Upvotes: 12

Related Questions