The dup system call duplicates an existing file descriptor, returning a new one that refers to the same base I / O object.
Dup allows shells to implement such commands:
ls existing-file non-existing-file > tmp1 2>&1
2> & 1 tells the shell to give the command to file descriptor 2, which is a duplicate of descriptor 1. (that is, stderr and stdout point to the same fd).
Now the error message for calling ls on a nonexistent file and the correct ls output in the existing file are displayed in the tmp1 file.
The following code example starts the wc program with a standard connection to the read end of the pipe.
int p[2]; char *argv[2]; argv[0] = "wc"; argv[1] = 0; pipe(p); if(fork() == 0) { close(STDIN); //CHILD CLOSING stdin dup(p[STDIN]); // copies the fd of read end of pipe into its fd ie 0 (STDIN) close(p[STDIN]); close(p[STDOUT]); exec("/bin/wc", argv); } else { write(p[STDOUT], "hello world\n", 12); close(p[STDIN]); close(p[STDOUT]); }
The child duplicates the end of reading on file descriptor 0, closes the file de scripts in p and execs wc. When wc reads from its standard input, it reads from the pipe.
This is how pipes are implemented using dup, so using a dup, you use a channel to build something else, that the beauty of system calls you build one thing after another using existing tools, this tool was built using something something else. In the end, system calls are the most basic tools you get in the kernel.
Greetings :)
Deepthought Jul 24. '12 at 17:20 2012-07-24 17:20
source share