Can someone explain what dup() in C does?

前端 未结 8 1095
不知归路
不知归路 2021-01-30 23:34

I know that dup, dup2, dup3 \"create a copy of the file descriptor oldfd\"(from man pages). However I can\'t digest it.

As I know file descriptors are just

8条回答
  •  醉酒成梦
    2021-01-30 23:50

    Let's say you're writing a shell program and you want to redirect stdin and stdout in a program you want to run. It could look something like this:

    fdin = open(infile, O_RDONLY);
    fdout = open(outfile, O_WRONLY);
    // Check for errors, send messages to stdout.
    ...
    int pid = fork(0);
    if(pid == 0) {
        close(0);
        dup(fdin);
        close(fdin);
        close(1);
        dup(fdout);
        close(fdout);
        execvp(program, argv);
    }
    // Parent process cleans up, maybe waits for child.
    ...
    

    dup2() is a little more convenient way to do it the close() dup() can be replaced by:

    dup2(fdin, 0);
    dup2(fdout, 1);
    

    The reason why you want to do this is that you want to report errors to stdout (or stderr) so you can't just close them and open a new file in the child process. Secondly, it would be a waste to do the fork if either open() call returned an error.

提交回复
热议问题