0

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;
            }
        }
}

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

It is usually encouraged to use STDOUT_FILENO and STDERR_FILENO instead of 1 and 2.
@FilipeGonçalves: Curiously, Posix itself in the examples for dup uses 1 and 2. Since the values 1 and 2 are specified by Posix, it makes no difference to portability but I agree that the longer names are more self-documenting. I just never remember how they're spelled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.