/* * Sample program for dup system call - No.41 * * dup, dup2 - duplicate a file descriptor * * Synopsis * #include * * int dup(int oldfd); * int dup2(int oldfd, int newfd); * * Description * dup and dup2 create a copy of the file descriptor oldfd. * After successful return of dup or dup2, the old and new * descriptors may be used interchangeably. They share locks, * file position pointers and flags; for example, if the file * posision is modified by using lseek on one of the descriptors, * the position is also changed for the other. * * The two descriptors do not share the close-on-exec flag, * however. */ #include #include #include #include main() { int fd1, fd2; char *s1 = "hello, "; char *s2 = "world\n"; char buf[BUFSIZ]; FILE *fp; fd1 = creat("foo", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); fd2 = dup(fd1); /* dup system call */ write(fd1, s1, strlen(s1)); write(fd2, s2, strlen(s2) + 1); close(fd1); system("cat foo"); exit(0); }