1dup functions and dup2 function
#include <unistd.h>
int dup (INTOLDFD);
int dup2 (INTOLDFD, int newfd);
DUPand thedup2can be used to copy an existing file descriptor so that two file descriptors point to the samefilestructural body. If two file descriptors point to the samefilestructure,File Status Flagand read-write locations save only one copy of thefilestructure, andfilethe reference count of the struct is2. If two timesOpenThe same file gets two file descriptors, then each descriptor corresponds to a differentfilestructure, can have differentFile Status Flagand read and write locations. Be careful to distinguish between the two cases.
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int FD, SAVE_FD;
Char msg[] = "This is a test\n";
FD =open ("Somefile", o_rdwr| O_creat, s_irusr| S_IWUSR);
if (fd<0) {
Perror ("open");
Exit (1);
}
SAVE_FD =dup (Stdout_fileno);
Dup2 (Fd,stdout_fileno);
Close (FD);
Write (Stdout_fileno,msg, strlen (msg));
Dup2 (Save_fd,stdout_fileno);
Write (Stdout_fileno,msg, strlen (msg));
Close (SAVE_FD);
return 0;
}
2VFS Virtual File System
On the essence of function call
Summarize:
A: the files on the operating disk are driven.
B: as long as the two file descriptor points to the same file structure, then the operation of the file is equivalent to the process appended to the file, does not overwrite the file content. If two files are opened with open at the same time , and there is no association between the two file descriptors that are put back, then a write operation will overwrite the other write operation at this time.
11Linux Server Programming: VFS virtual file system, DUP () function and dup2 () function