user1162954 user1162954 - 1 year ago 111
C Question

redirecting output of execvp into a file in C

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

if(wait(&status) == -1)
printf("ERROR REDIRECT\n");

gets created but there is nothing inside.What am I doing wrong?

Answer Source

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. */


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download