Search code examples
cforkexec

C - Redirecting IO of Child Process


I am trying to redirect the IO of a child process (after fork()) into a file, and I can't figure out why it isn't working.

Here's what I've done:

if(fork() == 0){
    execv(exe, (char*[]){ exe, "> temp.exe" });
    ...

And the executable runs, but it doesn't redirect to the file. I would appreciate it if anyone could explain what am I doing wrong, and how I should do it. I'm getting a feeling I need to redirect before the execv() but I have no idea how to.

Thanks in advance!


Solution

  • Shell redirections (like > file) are implemented by the shell. By using execve(), you are bypassing the shell; the child process will see "> temp.exe" in argv, and will attempt to process it as an argument.

    If you want to redirect output to a file, the easiest approach will be to implement that redirection yourself by opening the file after forking and using dup2() to move its file descriptor to standard output:

    if (fork() == 0) {
        int fd = open("temp.exe", O_CREAT | O_WRONLY, 0666);
        if (fd < 0) { handle error... exit(255); }
        dup2(fd, 1);
        close(fd);
        execv(exe, ...);
    }