How can I pass the redirection operator '>'

2019-03-06 08:55发布

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?

2条回答
ら.Afraid
2楼-- · 2019-03-06 09:16

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().

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-06 09:21

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 ">".

查看更多
登录 后发表回答