如何将重定向运算符“>”作为 execv 的参数传递?

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

在 linux 终端中,我可以输入

echo hello! > /path/to/file

我以为我可以使用 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;
}

但是,此代码不会将 'hello!' 写入文件,而这正是我希望它执行的操作。有没有其他方法可以使用 execv 和 echo 来做到这一点?

编辑: 我也尝试过使用 dup2 作为解决方案: #包括 #包括 #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;
}

然而,这也没有给我想要的结果。这会将 'hello!' 写入文件,但也会覆盖已写入文件的所有其他内容。怎么保证'hello!'会写到文件的END呢?

首先,> 等重定向运算符由 shell 解释,对 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) 没有任何意义。

其次,write_cmdchar* 的数组,但 '>'(注意单引号)的类型为 int。这实际上意味着您将一个整数放入一个数组中,该数组否则包含指向字符串的指针。您可能打算写 ">".

你可以,但只是间接的。

> 重定向运算符由 shell 解释; /bin/echo 不识别它,并将其视为要打印的另一个参数。

如果您希望 shell 执行重定向,您需要调用 /bin/sh 并将整个命令作为参数传递给它。

未经测试的代码如下:

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

或者,更简单地说,您可以使用 system()