Difference between revisions of "How to assign needed file descriptor to a file"
Jump to navigation
Jump to search
(Initial) |
|||
Line 16: | Line 16: | ||
</pre> | </pre> | ||
− | what's next? | + | what's next? In Linux there's a cool system call dup2() which assigns to a file referenced by one file descriptor some other one, given by the caller. |
+ | So the code would look like this: | ||
+ | <pre> | ||
+ | int fd; | ||
+ | |||
+ | fd = open_a_file(fd->file); | ||
+ | dup2(fd, fd->tgt_fd); | ||
+ | close(fd); | ||
+ | </pre> | ||
+ | |||
+ | [[Category:Under the hood]] |
Revision as of 09:35, 5 August 2014
Let's imagine we have opened a file and want it to have some exact descriptor number, not the one kernel gave to us.
The information we have is
struct fd { struct file *file; int tgt_fd; } *fd;
and we've just done the
int fd; fd = open_a_file(fd->file);
what's next? In Linux there's a cool system call dup2() which assigns to a file referenced by one file descriptor some other one, given by the caller. So the code would look like this:
int fd; fd = open_a_file(fd->file); dup2(fd, fd->tgt_fd); close(fd);