11Linux Server Programming: VFS virtual file system, DUP () function and dup2 () function

Source: Internet
Author: User



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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.