#include #include #include #include #include #include using namespace std; int main() { int fd, fd2, dupedFD; int i; char buf[]="This is a test writing to stdout from another file descriptor\n"; fd = open("duptest", O_WRONLY | O_CREAT, S_IRUSR| S_IWUSR|S_IRWXG|S_IRWXO); fd2 = open("duptest", O_WRONLY | O_CREAT, S_IRUSR| S_IWUSR|S_IRWXG|S_IRWXO); cout << "The first file descriptor I opened was " << fd << endl; cout << "The second file descriptor I opened was " << fd2 << endl; dupedFD = dup(fd); cout << "I duped a new one, it is " << dupedFD << endl; for(i = 0; i < 10; i++) { if (i%2) { write(fd,&i, sizeof(int)); } else { write(dupedFD,&i, sizeof(int)); } } cout << " file descriptor " << fd << " is at position " << lseek(fd, 0, SEEK_CUR) << endl; cout << " file descriptor " << dupedFD << " is at position " << lseek(dupedFD, 0, SEEK_CUR) << endl; // this is a different entry in the file table, even though it was opened // with the same command. cout << " file descriptor " << fd2 << " is at position " << lseek(fd2, 0, SEEK_CUR) << endl; // but move to the end of fd2 cout << "After seeking to the end of " << fd2 << endl; lseek(fd2, 0,SEEK_END); cout << " file descriptor " << fd2 << " is at position " << lseek(fd2, 0, SEEK_CUR) << endl; close(fd); close (dupedFD); fd = dup(STDOUT_FILENO); write(fd, buf, strlen(buf)); return 0; }