Can I get a really dumbed down explanation of the dup() function when it comes for duplicating file descriptors? I want to use pipe, but I have to also make the child to read from pipe(this is the easy part), but write data back to parent. Should I use another pipe, or can I use the same one?
From the man page:
The dup() system call creates a copy of the file descriptor oldfd, using the lowest-numbered unused descriptor for the new descriptor.
You can think of it as creating an alias. If the call has succeeded you'll have two file descriptors referring to the same resource (file, pipe or something else).
For your use case of communicating with a child process via pipes, you don't have to use dup
. All you need to do is to call pipe, fork and close unused ends of the pipe in child and parent processes.
dup() (and dup2() and dup3()) create duplicate file descriptors.
With the one argument dup() the OS chooses a free file descriptor number and makes it a duplicate of the one passed:
int dup_of_fd = dup(int fd);
With the two argument dup2() it is exactly the same except you tell it what file descriptor number you want to be used as the duplicate. If it's already in use (if 10 is already in use in this example) then it (10 here) is closed and reopened as the duplicate:
int dup_of_fd = dup2(fd, 10);
With the three argument dup3() (Linux specific) it's the same as dup2() except that you can pass flags/options.
In all cases the new (duplicated) file descriptor will be a different number to the old but reading from or writing to both will be exactly the same.
Note that when reading from 2 duplicated file descriptors the seek position is SHARED, so if you open a file and duplicate fd as dup_of_fd, then read 10 bytes from fd, then read 10 bytes from dup_of_fd, the bytes read from dup_of_fd will be bytes 11 to 20, even though it's the first read from that file descriptor number.
From the man page:
The dup() system call creates a copy of the file descriptor oldfd, using the lowest-numbered unused descriptor for the new descriptor.
You can think of it as creating an alias. If the call has succeeded you'll have two file descriptors referring to the same resource (file, pipe or something else).
For your use case of communicating with a child process via pipes, you don't have to use dup
. All you need to do is to call pipe, fork and close unused ends of the pipe in child and parent processes.
© 2022 - 2024 — McMap. All rights reserved.
socketpair()
for bidirectional communication. – Autogenous