3

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?

4
  • 1
    You aren't calling execvp properly. Commented Jan 30, 2012 at 20:20
  • Did you try the exact same code without the dup2? It should print to standard output. This test could help focus on the problem. Commented Jan 30, 2012 at 20:56
  • Have you considered exec'ing the command "ls > $filename"? Commented Jan 30, 2012 at 21:34
  • @dbeer: That won't work, exec... functions expect executable files, not shell commands. You could use system() though... Commented Jan 30, 2012 at 22:14

2 Answers 2

6

My guess is that the execvp doesn't work but since you don't handler errors you don't see it.

Try this:

char *const args[] = {"ls", NULL}; execvp(args[0], args); /* If this is reached execvp failed. */ perror("execvp"); 

Alternatively you can use compound literals:

execvp("ls", (char *[]){"ls", NULL}); 

Second idea: try to run things normally, without redirect and see how it works.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that and nothing gets printed... it seems that execvp gets executed succesfully.
@user1162954 - There is not a chance in the world your execvp is working. Take cnicutar fix and your stuff will work.
1

close fd before execvp. because the code after execvp never runs unless execvp fails.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.