简体   繁体   中英

Execute command with output redirection using exec command in C

I need execute a command which redirects output to /dev/null. How to execute commands like this using exec in C ?

My command is ls logs/ >/dev/null 2>/dev/null . To execute this command, I am first splitting the command with space as delimiter and then executing using exec. When executing >/dev/null 2>dev/null are passed as arguments to the script. How we can avoid this ?

I don't want to use system command to overcome this problem.

CODE :

static int
command_execute(char* command) {
        char **arguments = g_strsplit(command, " ", 32);
        pid_t child_pid;

        if( !arguments ) {
            status = COMMAND_PARSE_ERROR;
            goto EXIT;
        }

        if( (child_pid = fork() ) == -1 ) {
            status = CHILD_FORK_ERROR;
            goto EXIT;
        }

        if( child_pid == 0 ) {
            execvp(arguments[0], arguments);
        } else {
            waitpid(child_pid, &status, 0);
            if(status) {
                goto EXIT;
            }
        }
}

Redirections are not arguments to a command.

In a shell command containing redirects, the shell will set up the redirects before executing the command. If you want to mimic this behaviour, you need to do the same thing. In your child, before calling exec on the command, reopen stdout and stderr to /dev/null (or whatever you want to redirect them to).

If you need to extract the redirects from the provided string, you'll need to parse the string the same way the shell would (although you might chose to use a simpler syntax); interpret the redirects, and only pass the actual arguments to the command.

A simple way to reopen stdout is to use dup2 . The following outline needs error checking added:

int fd = open("/dev/null", O_WRONLY);
dup2(fd, 1);  /* Use 2 for stderr. Or use STDOUT_FILENO and STDERR_FILENO */
close(fd);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM