为什么使用 execl 而不是 system 会阻止我的程序运行?

Why does using `execl` instead of `system` stops my program from working?

我正在尝试使用管道进行基本 IPC。我花了几个小时在互联网上搜索,做这做那,阅读 API 文档,最后得到下面的代码。但它不起作用,正如我所预料的那样。只要能帮助我编写代码 'work',我将不胜感激。

<编辑>
我刚刚发现使用 system 而不是 execl 可以使我的程序 运行 完全符合预期。那么,当我使用 execl 时出现了什么问题,而 system 函数却没有发生这种情况?

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

int main(void){
    int hInPipe[2];
    int hOutPipe[2];
    FILE *hInFile;
    FILE *hOutFile;
    char *s;

    pipe(hInPipe);
    pipe(hOutPipe);
    if(fork()){
        close(hInPipe[0]);
        close(hOutPipe[1]);
        hInFile=fdopen(hInPipe[1],"w");
        fprintf(hInFile,"2^100\n");
        fclose(hInFile);
        hOutFile=fdopen(hOutPipe[0],"r");
        fscanf(hOutFile,"%ms",&s);
        fclose(hOutFile);
        printf("%s\n",s);
        free(s);
    }else{
        dup2(hInPipe[0],STDIN_FILENO);
        dup2(hOutPipe[1],STDOUT_FILENO);
        close(hInPipe[0]);
        close(hInPipe[1]);
        close(hOutPipe[0]);
        close(hOutPipe[1]);

        system("bc -q");/*this works*/
        /*execl("bc","-q",NULL);*/ /*but this doesn't*/
    }
}

阅读精美的手册页。 :)

execl(const char *path, const char *arg0, ... /*, (char *)0 */);

arg0(又名 argv[0],程序被告知在其下调用的名称)不是与路径相同的参数(所述程序的可执行文件)。此外,execl 将全限定路径名作为其第一个参数。

因此,您需要:

execl("/usr/bin/bc", "bc", "-q", NULL);

...或者,要在 PATH 中搜索 bc 而不是对位置进行硬编码:

execlp("bc", "bc", "-q", NULL);