Featured Post

Friday, March 25, 2016

dup and dup2 system calls

dup() system call is used to create a duplicate file descriptor for a give file descriptor. The new file descriptor will take the lowest file descriptor value from file descriptor table.

for example

   void main()
   {
      int fd1,fd2;
       fd1=open("hello.txt",O_WRONLY|O_CREAT,S_IRWRXU);
       if(fd1<0)
       {
       printf("error opening the file");
      exit(1);
      }
     fd2=dup(fd1);/* fd2 will take lowest file descriptor value */
     printf("original file descriptor is %d \t new file descriptor is %d",fd1,fd2);
   }

original file descriptor is 6       new file descriptor is 11

dup2() system call is also used to create a new file descriptor for a give file descriptor. But here we specify the new file descriptor value force fully. If the new value not available then it will be freed by the Unix OS.

void main()
   {
      int fd1,fd2;
       fd1=open("hello.txt",O_WRONLY|O_CREAT,S_IRWRXU);
       if(fd1<0)
       {
       printf("error opening the file");
      exit(1);
      }
    fd2=dup2(fd1,5); /* imagine that fd1 value is 10 and we expecting fd2 value to be 5 */
     printf("original file descriptor is %d \t new file descriptor is %d",fd1,fd2);
   }


original file descriptor is 10      new file descriptor is 5



any comments or queries? 




Unix operating system Linux operating system shell programming bourn shell kourne shell c shell difference between unix and linux operating system , history of UNIX, red hat operating system. UNIX OS architecture , kernel utility programs , file handling process handling inter process communication pipes shared memory message queues socket programming TCP/IP , UDP programming , One to One chat Application , Basic shell program to add two numbers , echo function , while loops clear gt lt le ge ne eq if fi while do done case array in unix strings , cut copy paste cat dir pwd getcwd chdir command read write stat lseek fstat flock mechanism.even or add program vi editor command ni vi editor command mode esc mode insert mode aa dd x :q :wq :w. dup and dup2 system call duplicate file descriptor


No comments:

Post a Comment