Question

I got this code clip from APUE,

if (dup2(clfd, STDOUT_FILENO) != STDOUT_FILENO ||
          dup2(clfd, STDERR_FILENO) != STDERR_FILENO) {
            syslog(LOG_ERR, "ruptimed: unexpected error");
            exit(1);
        }

Which will redirect all output, stderr and stdout to remote socket, which is writable through clfd.

But how could that work ? You're redirecting two FDs to a single one.

Was it helpful?

Solution

But how could that work ? You're redirecting two FDs to a single one

There's no problem with that. The standard says:

int dup2(int fildes, int fildes2);

The dup2() function shall cause the file descriptor fildes2 to refer to the same open file description as the file descriptor fildes. If fildes2 is already a valid open file descriptor, it shall be closed first.

At no point does it mention anything about multiple descriptors referring to the same destination being illegal.

The kernel simply has to point multiple file descriptors from the process to the same entry in the system-wide open file table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top