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

元气小坏坏 提交于 2019-12-02 11:22:13
Martin Törnwall

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

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

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