【问题标题】:Why does using `execl` instead of `system` stops my program from working?为什么使用 `execl` 而不是 `system` 会阻止我的程序工作?
【发布时间】:2015-07-27 12:56:51
【问题描述】:

我正在尝试使用管道进行基本的 IPC。我花了几个小时在互联网上搜索,做这做那,阅读 API 文档,最后得到了下面的代码。但它不起作用,正如我所预料的那样。非常感谢让我的代码“工作”的任何帮助。


我刚刚发现使用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*/
    }
}

【问题讨论】:

  • 简化问题。将bc 替换为cat,将fscanf 替换为read。并添加错误检查。
  • 另外,不要写入未初始化的指针,或者释放它。
  • “它不起作用,正如我所预料的那样”是什么意思?实际发生了什么?你期待什么?
  • @JohnBollinger 我确实写了很多 C,但是我在这种编程方面的经验几乎为零,与操作系统进行了深入的交互。我尝试的示例代码实际上几乎是我现在需要实现的一切。经过数小时的混乱,我认为我得到了 98% 的正确率,但是计算机对于最后 2% 的失误并不是很容易接受。我只需要一个小小的调整就可以完成我的解决方案。
  • @WilliamPursell 那么我的程序的哪一部分出了问题?那里的 fscanf 线对我来说似乎没问题。我用%ms而不是%s,所以没有写入未初始化的指针。

标签: c linux unix pipe ipc


【解决方案1】:

阅读精美的手册页。 :)

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2022-01-16
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    相关资源
    最近更新 更多