Difference between revisions of "How to assign needed file descriptor to a file"

From CRIU
Jump to navigation Jump to search
m
Line 23: Line 23:
 
fd = open_a_file(fd->file);
 
fd = open_a_file(fd->file);
 
dup2(fd, fd->tgt_fd);
 
dup2(fd, fd->tgt_fd);
 +
close(fd);
 +
</pre>
 +
 +
Now let's remember, that a file can be opened multiple times in one task, this is happens when you e.g. start a shell. One of the <code>/dev/tty</code> or alike files will sit under 0, 1 and 2 descriptors. Not a big deal, we just expand the <code>struct fd</code>
 +
 +
<pre>
 +
struct fd {
 +
struct file *file;
 +
int n_fds;
 +
int *tgt_fds;
 +
} *fd;
 +
</pre>
 +
 +
and the code itself:
 +
 +
<pre>
 +
int fd, i;
 +
 +
fd = open_a_file(fd->file);
 +
for (i = 0; i < fd->n_fds; i++)
 +
dup2(fd, fd->tgt_fds[i]);
 
close(fd);
 
close(fd);
 
</pre>
 
</pre>
  
 
[[Category:Under the hood]]
 
[[Category:Under the hood]]

Revision as of 09:53, 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);

Now let's remember, that a file can be opened multiple times in one task, this is happens when you e.g. start a shell. One of the /dev/tty or alike files will sit under 0, 1 and 2 descriptors. Not a big deal, we just expand the struct fd

	struct fd {
		struct file *file;
		int n_fds;
		int *tgt_fds;
	} *fd;

and the code itself:

	int fd, i;

	fd = open_a_file(fd->file);
	for (i = 0; i < fd->n_fds; i++)
		dup2(fd, fd->tgt_fds[i]);
	close(fd);