Search code examples
cgrepexecv

Passing ">>" as an execv argument?


I am trying to pass some arguments into an execv call:

char *const paramList[] = {"/bin/grep", "-rn", "comrade", 
                           "/home/sgspectra/Documents/testing_grep/",
                           ">>", "output.txt", NULL};

I believe that ">>" and "output.txt" are being read as arguments for additional directories to search through instead of to send the output to "output.txt". Is it possible to send an argument that would indicate only the previous argument is a directory?


Solution

  • When you type a command into a shell that supports >>, the shell handles the “>> filename’ in your command itself. Then it removes that text from the command line. The rest of the command line (the parts that were not removed, including your command and any other arguments), are then passed to execv or one of its related functions.

    To do the same thing, what you need to do is something along the lines of:

    • Call fork to create a subprocess of your process.
    • In the parent (where fork returns a process ID for the child it created), go on with other execution—the parent might wait for the child or it might go on to do other things.
    • In the child (where fork returns 0), close file descriptor 1 (standard output) and use openat to open output.txt in append mode at file descriptor 1. Then call execv.

    (Caveat emptor: It has been a few decades since I did things like this, so my memory may have changed, and the precise steps required may have changed.)

    A cruder but easier-to-code option is to use execv to execute a shell, which you pass parameters requesting it to interpret and execute your command, including the redirection, as shown in this answer.