Results 1 to 2 of 2
Hi,
There is something in this code i dont undstand. This code opens a file wiht the name test.txt, and if it for some reason cant open the file , ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 05-26-2003 #1Just Joined!
- Join Date
- May 2003
- Posts
- 6
need help
Hi,
There is something in this code i dont undstand. This code opens a file wiht the name test.txt, and if it for some reason cant open the file , it gives an error message. But what does it do in this part:
Code:close(1); dup2(fd, 1); close(fd); if (execvp(argv[0], argv) == -1) printf("EXEC ERROR\n"); waitpid(-1, &status, 0);
Code:int main(int argc, char *argv[]) { int fd; int status; char test[80] = "ls"; argv[0] = test; if ((fd = open("/home/test/test.txt", O_WRONLY)) == -1) printf("ERROR\n"); close(1); dup2(fd, 1); close(fd); if (execvp(argv[0], argv) == -1) printf("EXEC ERROR\n"); waitpid(-1, &status, 0); return(0); }
- 05-26-2003 #2Linux Guru
- Join Date
- Oct 2001
- Location
- Täby, Sweden
- Posts
- 7,578
The close, dup2, close lines puts the opened file (/home/test/test.txt) on file descriptor 1, ie. standard output. The execvp line the execs ls, so that the output of ls is put into the test.txt file. The waitpid line, however, has no logical function here, though. If execvp succeeds, it won't be called at all, but it's not like that would actually matters, since there wouldn't be any child processes to wait for whether execvp succeeds or not.


Reply With Quote
