简体   繁体   English

为什么使用`execl`而不是`system`会使我的程序无法正常工作?

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

I'm trying to do basic IPC using pipes. 我正在尝试使用管道进行基本IPC。 I spent hours searching the internet, doing this and that, reading the API documentations, and ended up with the code below. 我花了数小时在互联网上搜索,执行此操作,阅读API文档,最后得到以下代码。 But it does not work, as I quite expected. 但这不起作用,正如我所期望的那样。 Just any help making my code 'work' would be many thanks. 非常感谢使我的代码“正常工作”的任何帮助。

<edit> <编辑>
I've just found that using system instead of execl makes my program run perfectly as expected. 我刚刚发现使用system而不是execl可以使我的程序按预期运行。 So what is going wrong here when I use execl , while it doesn't happen with the system function? 那么,当我使用execl ,这出了什么问题,而system功能却没有发生?
</edit> </编辑>

#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*/
    }
}

Read the fine man page. 阅读详细手册页。 :) :)

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

arg0 (aka argv[0], the name the program is told it was invoked under) is not the same argument as the path (the location of the executable for said program). arg0 (又名的argv [0],该程序被告知这是下调用的名称)是一样的参数作为路径(可执行的用于所述程序中的位置)。 Moreover, execl takes, as its first argument, a fully-qualified pathname. 而且, execl将标准路径名作为第一个参数。

Thus, you want: 因此,您想要:

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

...or, to search the PATH for bc rather than hardcoding a location: ...或者,在PATH中搜索bc而不是对位置进行硬编码:

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

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

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