redirecting output of execvp into a file in C

前提是你 提交于 2019-12-24 01:19:04

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9070177/redirecting-output-of-execvp-into-a-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!