Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relation between dup() and close() system calls?

I've searched this topic on web and came across this explain but I can not get the idea behind of it. Code and explanation is as follows..

#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd); //** LINE F **//
...

/*The example above closes standard output for the current
processes,re-assigns standard output to go to the file referenced by pfd,
and closes the original file descriptor to clean up.*/

What does LINE F do? Why it is crucial?

like image 615
Furkan Buyrukoğlu Avatar asked Oct 16 '25 16:10

Furkan Buyrukoğlu


1 Answers

The goal of code like this is to change the file descriptor number that references a currently open file. dup allows you to create a new file descriptor number which references the same open file as another file descriptor. The dup function guarantees that it will use the lowest possible number. close makes a file descriptor available. This combination of behaviors allows for this sequence of operations:

close(1);  // Make file descriptor 1 available.
dup(pfd);  // Make file descriptor 1 refer to the same file as pfd.
           // This assumes that file descriptor 0 is currently unavailable, so
           // it won't be used.  If file descriptor 0 was available, then
           // dup would have used 0 instead.
close(pfd); // Make file descriptor pfd available.

At the end, file descriptor 1 now references the same file that pfd used to, and the pfd file descriptor is not used. The reference has effectively been transferred from file descriptor pfd to file descriptor 1.

In some cases, close(pfd) may not be strictly necessary. Having two file descriptors that refer to the same file may be fine. However, in many cases, this can cause undesirable or unexpected behavior.

like image 188
Vaughn Cato Avatar answered Oct 18 '25 16:10

Vaughn Cato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!