简体   繁体   English

execvp shell 命令与 shell output 重定向不起作用

[英]execvp shell command with shell output redirection does not work

I have developed the following code: main:我开发了以下代码:主要:

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

int main()
{
    char *const args[] = {"/bin/ls", "> test.txt 2>&1", NULL};
    execvp(args[0], args);

    /* If this is reached execvp failed. */

    perror("execvp");
    return 0;
}

I need to execute this shell command: /bin/ls > test.txt 2>&1 but I have got an error:我需要执行这个 shell 命令: /bin/ls > test.txt 2>&1但我有一个错误:

$gcc -o main main.c 
$ vi main.c
$ gcc -o main main.c 
$ ./main 
/bin/ls: cannot access '> test.txt 2>&1': No such file or directory
$ 

Why it returns /bin/ls: cannot access '> test.txt 2>&1': No such file or directory ?为什么它返回/bin/ls: cannot access '> test.txt 2>&1': No such file or directory Have you a solution to fix that?你有解决方案吗?

no that doesn't work.不,那是行不通的。 Redirecting is a function of your shell.重定向是 shell 的 function。 And by using one of the exec functions, you bypass the shell completely.通过使用其中一个exec函数,您可以完全绕过 shell。 So you need to handle redirection yourself.所以你需要自己处理重定向。

int out = open("test.txt", O_WRONLY | O_CREAT, 0644);
dup2(out, 1);
dup2(out, 2);
close(out);
execvp(args[0], args);

but drop the second item in args first.但首先将第二项放在 args 中。

This will open the output file and duplicate it to stdin and stdout like the shell would do.这将打开 output 文件并将其复制到标准输入和标准输出,就像 shell 一样。 Finally close the original descriptor as that is no longer needed.最后关闭原始描述符,因为不再需要它。

I left out error checking, but you should definitely add that of course.我省略了错误检查,但你当然应该添加它。

Redirections are interpreted by the shell.重定向由 shell 解释。 But execvp() does not run a shell.但是execvp()不运行 shell。 It runs an executable.它运行一个可执行文件。 You can do what is done internally by system() by calling "sh -c":您可以通过调用“sh -c”来执行system()内部完成的操作:

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

int main(void)
{
    char *const args[] = {"/bin/sh", "-c", "/bin/ls > test.txt 2>&1", NULL};
    execvp(args[0], args);

    /* If this is reached execvp failed. */

    perror("execvp");
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM