带有 shell 输出重定向的 execvp shell 命令不起作用

问题描述

我开发了以下代码: 主要:

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

我需要执行这个 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
$ 

为什么它返回 /bin/ls: cannot access '> test.txt 2>&1': No such file or directory ?你有解决办法吗?

解决方法

不,那行不通。重定向是 shell 的一个功能。通过使用 exec 函数之一,您可以完全绕过 shell。所以你需要自己处理重定向。

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

但首先删除 args 中的第二项。

这将打开输出文件并将其复制到标准输入和标准输出,就像 shell 所做的那样。最后关闭原始描述符,因为不再需要它。

我省略了错误检查,但您当然应该添加它。

,

重定向由外壳程序解释。但是 execvp() 不运行 shell。它运行一个可执行文件。您可以通过调用“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;
}