I am working on a Shell Command Execution Simulation in C.
I'm trying to redirect the output of execvp function into a file. The output looks okay when printed to terminal, but when tried to redirect it to a txt file, there is no output visible on the output.txt file that is created.
Here is how the code looks:
int file = open("output.txt", O_WRONLY | O_CREAT);
if (file == -1) {
perror("open");
exit(EXIT_FAILURE);
}
if (dup2(file, STDOUT_FILENO) == -1) {
perror("dup2");
exit(EXIT_FAILURE);
}
char* command1= "grep";
char* myList[]={"grep", "URL", NULL};
close(file);
execvp(command1, myList);
perror("execvp");
exit(EXIT_FAILURE);
FOUND SOLUTION:
Apparently the problem caused because I forgot to close read and write side of the pipe.
I should've added:
close(fd[0]);
close(fd[1]);
after using dup2 function.
Thanks for everyone who tried to help me even though my problem was could not be solved by the info I gave.
is not correct.
You are not properly setting the file's permission bits, so later use of the file likely causes problems.
When creating a file,
open()requires amodeargument:Instead of
you should probably have something like:
The current
output.txtfile likely has some strange permissions that could be causing problems. Delete the file, and update your code to ensure the file is created with controlled permissions.