如何传递重定向运算符'>'作为execv的参数? [英] How can I pass the redirection operator '>' as an argument for execv?

查看:225
本文介绍了如何传递重定向运算符'>'作为execv的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在linux终端中,我可以输入

In the linux terminal, I can type

echo hello! > /path/to/file

我想我可以使用execv来做同样的事情:

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

但是,此代码不会在文件中写入 hello!,这就是我想要的。

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?

编辑:
我也尝试过使用dup2作为解决方案:
# include
#include
#include

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

但是,这也不能给我想要的结果。这样会在文件中写入 hello!,但也会覆盖文件中已经写入的所有其他内容。如何保证将 hello!写入文件的末尾?

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?

推荐答案

首先,重定向运算符像> 之类的东西由外壳程序解释,对 execve(2)(或者回声)。您可以尝试使用 system(3),或者您可以自行设置重定向通过使用 dup2(2)(请参见此问题)。

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

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

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

这篇关于如何传递重定向运算符'&gt;'作为execv的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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