Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Advanced I/O-dup/dup2

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report