/* * How to handle the case where we have a file open on a channel other * than fd 1 but we want to redirect stdout to that. * Similar to spawndup.c but here we are using the slightly easier and * slightly more-general function dup2(). */ #include #include #include #include #include int main() { int x = fork(); if (x == -1) { perror("fork"); return(1); } else if (x == 0) { /* child */ int fd; if ((fd = open("file", O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0) { perror("file"); return(1); } dup2(fd, 1); close(fd); execl("/bin/ls", "ls", (char *)NULL); perror("/bin/ls"); return(1); } else { /* parent */ int status; wait(&status); printf("Still here, although not for long\n"); return(0); } }