I don't know what I am doing wrong... but here is the snippet of code that is being executed:
if (fork() == 0)
{
// child
int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
execvp("ls","ls");
close(fd);
exit(0);
}
if(wait(&status) == -1)
{
printf("ERROR REDIRECT\n");
}
fileName
gets created but there is nothing inside.What am I doing wrong?
My guess is that the execvp doesn't work but since you don't handler errors you don't see it.
Try this:
Alternatively you can use compound literals:
Second idea: try to run things normally, without redirect and see how it works.
close fd before execvp. because the code after execvp never runs unless execvp fails.