linux 下dup和dup2(Linux under DUP and dup2).docVIP

  • 2
  • 0
  • 约 15页
  • 2017-10-05 发布于河南
  • 举报

linux 下dup和dup2(Linux under DUP and dup2).doc

linux 下dup和dup2(Linux under DUP and dup2)

linux 下dup和dup2(Linux under DUP and dup2) DUP and dup2 are also two very useful calls that are used to copy descriptors of a file. They are often used to redirect processes stdin, stdout, and stderr. The prototype of these two functions is as follows: #include unistd.h Int dup (int oldfd); Int dup2 (int, oldfd, int, targetfd) Using the function DUP, we can copy a descriptor. A given descriptor is passed to the function, and it returns a new descriptor, This new descriptor is a copy of the descriptor passed to it. This means that the two descriptors share the same data structure. Such as, If we perform lseek operations on a file descriptor, the location of the first file we get is the same as the second. Here is a snippet of code to illustrate how the DUP function uses methods: Int, FD1, fd2; ... Fd2 = dup (FD1); It is important to note that we can create a descriptor before calling fork, which is the same as calling the DUP to build the descriptor, The child process also receives a copy of the descriptor. The dup2 function is similar to the DUP function, but the dup2 function allows the caller to specify the ID of a valid descriptor and target descriptor. When the dup2 function returns successfully, The target descriptor (the second parameter of the dup2 function) will become a copy of the source descriptor (the first parameter of the dup2 function), in other words, The two file descriptors now point to the same file, and are the files pointed to by the first argument of the function. Lets illustrate with a piece of code: Int oldfd; Oldfd = open (app_log (O_RDWR O_CREATE |), 0644); Dup2 (oldfd, 1); Close (oldfd); In this example, we open a new file called app_log, and receive a file descriptor called fd1. We call the dup2 function, The arguments are oldfd and 1, which results in the replacement of the file descriptor represented by 1 (that is, stdout, because the standard output file has a ID of 1) instead of our newly opened file descriptor. Anything written to std

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档