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.