重定向execvp的输出转换成在C文件 [英] redirecting output of execvp into a file in C

查看:553
本文介绍了重定向execvp的输出转换成在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我做错了......但这里是正在执行的code的片段:

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");
    }

文件名获取创建,但没有什么inside.What我做错了?

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

推荐答案

我的猜测是,execvp不工作,但因为你没有处理程序错误,你看不到它。

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

试试这个:

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.

这篇关于重定向execvp的输出转换成在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆