How can I pass the redirection operator '>' as an argument for execv?

旧城冷巷雨未停 提交于 2019-12-02 18:19:10

问题


In the linux terminal, I can type

echo hello! > /path/to/file

I thought I would be able to do the same thing using execv:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(void){
    char *write_cmd[] = { "echo", "hello!", ">", "/path/to/file", NULL};
    if (fork() == 0){
        execv("/bin/echo", write_cmd);
    }
    else{
        sleep(1);
    }
    return 0;
}

However, this code doesn't write 'hello!' to the file, which is what I want it to do. Is there another way to do this using execv and echo?

Edit: I've tried using dup2 as a solution as well: #include #include #include

int main(void){
    char *write_cmd[] = { "echo", "hello!", NULL };
    if (fork() == 0){
        int tmpFd = open("/path/to/file", O_WRONLY);
        dup2(tmpFd, 1);
        execv("/bin/echo", write_cmd);
        close(tmpFd);
        exit(0);
    }
    else{
        sleep(1);
    }
    return 0;
}

However, this doesn't give me the result I want either. This writes 'hello!' to the file, but it also overwrites everything else that was already written on the file. How can I guarantee that 'hello!' will be written to the END of the file?


回答1:


First of all, redirection operators like > are interpreted by the shell, and mean nothing to execve(2) (or to echo, for that matter). You could try using system(3) instead, or you could set up the redirection yourself by opening the output file and setting standard out to the resulting file descriptor using dup2(2) (see this question).

Secondly, write_cmd is an array of char*, but '>' (note the single quotes) has type int. This effectively means that you are putting an integer in an array that otherwise contains pointers to strings. You probably meant to write ">".




回答2:


You can, but only indirectly.

The > redirection operator is interpreted by the shell; /bin/echo doesn't recognize it, and treats it as just another argument to be printed.

If you want the shell to do the redirection, you need to invoke /bin/sh and pass the entire command to it as an argument.

Untested code follows:

char *write_cmd[] = { "/bin/sh", "-c", "echo hello! > /path/to/file", NULL };
// ...
execv("/bin/sh", write_cmd);

Or, more simply, you could use system().



来源:https://stackoverflow.com/questions/28490290/how-can-i-pass-the-redirection-operator-as-an-argument-for-execv

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