80 likes | 356 Views
Minishell 2. InKwan Yu iyu@cise.ufl.edu. Topics. Piping dup() dup2() Quiz & QnA. Piping. int pfd[2]; pipe(pfd); // note: called in parent if (fork() == 0) { // first child close(pfd[0]); dup2(pfd[1], STDOUT_FILENO); close(pfd[1]); …. }
E N D
Minishell 2 InKwan Yu iyu@cise.ufl.edu
Topics • Piping • dup() • dup2() • Quiz & QnA
Piping int pfd[2]; pipe(pfd); // note: called in parent if (fork() == 0) { // first child close(pfd[0]); dup2(pfd[1], STDOUT_FILENO); close(pfd[1]); …. } if (fork() == 0) { // second child close(pfd[1]); dup2(pfd[0], STDIN_FILENO); close(pfd[0]); …. } close(pfd[0]); close(pfd[1]); // don't forget this
Piping Parent's table fd 0 pipe 0 fd 1 fd 2 File access fd 3 File pos File size fd 4 refcnt==1 File type Child 1's table ... ... stdin fd 0 stdout pipe 1 fd 1 fd 2 fd 3 File pos fd 4 refcnt==1 Child 2's table ... stdin fd 0 stdout fd 1 fd 2 fd 3 fd 4
dup() • dup(fd) • Finds the first empty slot in the process file descriptor table and duplicates fd to it • To duplicate an FD to STDOUT • Close STDOUT and make sure it’s the first empty slot (STDIN should be open) • close(1); • dup(fd);
dup2() • dup(fromfd, tofd) • Closes the target descriptor if it’s already open • Duplicates fromfd to tofd • To duplicate an FD to STDOUT • dup2(fd, 1); • dup2() is easier than dup()
dup()/dup2() Applications • CGIs • Web server redirects a network socket descriptor STDIN and STDOUT of a CGI • Internet Super Daemon (inetd) • inetd brings a network server when needed. • ftpd, telnetd, etc support this feature • Network socket descriptor is redirected to STDIN and STDOUT