-1

This code takes 2 files and puts the results into a third file. It does this just fine but what's causing me concern is that the last printf is not printing to the screen. The first one prints just fine. This tells me I didn't restore the stdout correctly?

int main (int argc, char *argv[])
{
    char *join[4]={"cat", "file1.txt","file2.txt", 0};
    int id, fd, status;

    printf("fd=%d\n", fd); //this one prints to screen

    fd=dup(1); //save stdout
    close(1); close stdout

    FILE *out=fopen("output.c", "a"); //this is where the output should go

    id=fork(); //0 for child

    if (id>0) //parent process
    {
        waitpid(id, &status, WUNTRACED);
    }

    else if (id==0) //child process
    {
        execvp(join[0], join);
    }

    else //error
    {
        printf("error occured");
    }


    close(1);
    dup2(fd, 1);
    fclose(out);


    printf("fd=%d\n", fd); //this one doesn't print to screen


return 0;

}
haiku_vi
  • 439
  • 1
  • 5
  • 6
  • 1
    `fd` is never given a value, so you are putting undefined value into the fileids. After closing you never try to restore the original stdout, so why would you expect it to magically work? – John3136 Feb 10 '17 at 02:29
  • Your skeletal code is missing quite a lot of important steps. It isn't an MCVE ([MCVE]), though we can, just about, make out what you're up to and fill in the blanks. It is best if we don't have to guess and grimace about what is not done (initialize `fd`, for example, or wonder what significance `out` is supposed to have), and hope for the best. – Jonathan Leffler Feb 10 '17 at 02:30
  • Sorry, still new to this. I made some edits and still not seeing the 2nd print statement and now I can't see what I'm typing in the terminal now. I thought I restored the output with `dup2(fd, 1)`? – haiku_vi Feb 10 '17 at 18:13

2 Answers2

3

You need to save stdout so you can get it back later.

// save stdout
int sv_stdout = dup(STDOUT_FILENO);
// close stdout
close(STDOUT_FILENO);

// do stuff

// restore stdout
dup2(sv_stdout, STDOUT_FILENO);
bzrr
  • 1,490
  • 3
  • 20
  • 39
0

execvp never returns. Your process is replaced by the cat process. When that process exits, you get your shell prompt back. See man page for exec. Google an example of fork/exec to see how to run multiple processes. Or use system() which does this for you.

Lori
  • 1,392
  • 1
  • 21
  • 29
Frank
  • 1