代码之家  ›  专栏  ›  技术社区  ›  SamratV

如何正确使用c中的execvpe()?

  •  1
  • SamratV  · 技术社区  · 7 年前

    我正在尝试使用 execvpe() 函数。我的代码文件位于 /code/Solution.c . 我用命令编译了它 gcc /code/Solution.c -o /code/Solution .我想运行编译后的代码,即 /code/Solution 文件使用 执行程序() . 当我手动运行它时,我使用命令 ./code/Solution < /input/1.txt &> /stdout/1.txt 它很好地工作,但是当我尝试用同样的编程方式来做时,它会卡住(程序永远不会结束)。 执行程序() . 以下是我的代码:

    #define _GNU_SOURCE
    #include<unistd.h>
    #include<stdio.h>
    
    int main(){
        char *args[] = {"./Solution", "<", "/input/1.txt", "&>", "/stdout/1.txt", NULL};
        char *env[]  = {"PATH=/code", NULL};
        int x = execvpe("Solution", args, env);
        printf("%d\n", x);
        return 0;
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Petr Skocik    7 年前

    重定向运算符不是传递给内核的参数。 它们是一个shell语言特性。

    < /input/1.txt 或者更明确地说 0</input/1.txt 表示大约(根据您自己的喜好报告错误):

    int fd;
    if(0>(fd=open("/input/1.txt",O_RDONLY))){ perror("open"); /*...*/ }
    if(0>dup2(fd,0)){ perror("dup"); /*...*/ }
    if(fd!=0) close(fd);
    

    虽然 &>/stdout/1.txt 或更具位置性/明确性 1> /stdout/1.txt 2>&1 方法

    // 1> /stdout/1.txt
    if(0>(fd=open("/stdout/1.txt",O_WRONLY|O_TRUNC))){ perror("open"); /*...*/ }
    if(0>dup2(fd,1)){ perror("dup"); /*...*/ }
    if(fd!=1) close(fd);
    
    // 2>&1
    if(0>dup2(1,2)){ perror("dup"); /*...*/ }