Sunday, August 17, 2014

Unix Prog: File Sharing(1)

1. dup and dup2: duplicate the file descriptor
fd1 is duplicated then it points to file table entry where fd0 points to.
Then any operation against fd0 and fd1 will be acted on same file table entry, both descriptors share the file status flags, current file offset etc.

fileio.c:
 #include<unistd.h>  
 #include<fcntl.h>  
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<errno.h>  
   
 int main()  
 {  
  char buff[] = "Hello world!";  
  int fd1, fd2, fd3;  
   
  if((fd1 = open("test.txt", O_RDWR)) == -1) {  
   printf("open error!\n");  
   exit(1);  
  }  
   
  // Use dup to return the lowest file descriptor number in system  
  // After calling dup, it will create a file descriptor which points  
  // to the same file table entry as fd1 points to  
  if((fd2 = dup(fd1)) == -1) {  
   printf("duplication error!");  
   exit(2);  
  }  
   
  // Use dup2 to specify the file descriptor we want to use, in this  
  // case, 5. If 5 is already used, system will close(5), then allocate  
  // this file descriptor to us. In the end, 5 and fd1 will point to  
  // the same file table entry.  
  if((fd3 = dup2(fd1, 5)) == -1) {  
   printf("duplication error!");  
   exit(3);  
  }  
   
  // Right now, fd1, fd2, and fd3 are pointing to same file table entry  
  printf("fd1: %d, fd2: %d, fd3: %d\n", fd1, fd2, fd3);  
   
  // After writing buff with fd1, file table entry will increase current offset  
  if(write(fd1, buff, 12) != 12) {  
   printf("write error!\n");  
   exit(4);  
  }  
   
  // After writing buff with fd2, file table entry will increase current offset  
  // Since it is operating the same file table entry, the current offset will be  
  // increased based on the result in last operation against fd1  
  if(write(fd2, buff, 12) != 12) {  
   printf("write error!\n");  
   exit(4);  
  }  
   
  // Similar as above  
  if(write(fd3, buff, 12) != 12) {  
   printf("write error!\n");  
   exit(4);  
  }  
   
  close(fd1);  
  close(fd2);  
  close(fd3);  
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 fd1: 3, fd2: 4, fd3: 5  
 ubuntu@ip-172-31-23-227:~$ cat test.txt  
 Hello world!Hello world!Hello world!  

No comments:

Post a Comment