Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Advanced I/O-dup/dup2

Shulou Source: shulou.com Published: 2022-06-01 04:02:50 09月17日 Update

Dup/dup2

Dup/dup2 are two methods for specifying file operators, which work similarly, with two file descriptors pointing to the same file structure, so that the reference count of file is 2, so we need to manually close the other one that is not needed when we use it.

Dup:

The purpose of dup is to point the file descriptor to the smallest file descriptor.

# include int dup (int oldfd); int dup2 (int oldfd, int newfd)

Because it's relatively simple, let's look at it from the code.

1 # include 2 # include 3 # include 4 # include 5 # include 6 # include 7 # define _ PATH_ ". / test.log" 8 9 10 int main () 11 {12 umask (0); 13 int fd=open (_ PATH_,O_CREAT | Orange WRONLY 0644); / / Open a new file 14 if (fd0) 27 {28 buf [size] ='\ 0' 29} 30 if (strncmp (buf, "quit", 4) = = 0) 31 {32 break; 31 {32 break; 33} 34 printf ("% s", buf); / / printf will be output to 35 fflush (stdout) in file descriptor 1; 36} 37 close (1); 38 return 0; 39}

Effect picture

Dup2:

1 # include 2 # include 3 # include 4 # include 5 # include 6 # include 7 # define _ PATH_ ". / test.log" 8 9 int main () 10 {11 umask (0); 12 int fd = open (_ PATH_,O_CREAT | Orange WRONLY 0644); 13 if (fd

Tags: File point output two function minimum similar code information only manual operator effect effect graph method method time standard look structure Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Docker macOS Redmi MySQL