-
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);
}
-
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.