【问题标题】:Using popen to compile external program使用popen编译外部程序
【发布时间】:2016-01-03 05:55:49
【问题描述】:

我正在创建一个在线法官。为此,我正在编写一个 CGI c 脚本,它获取程序内容并编译程序。

这是我编译外部 c 程序的函数。

char *compile_program(char *compile_script){
printf("%s\n", compile_script);
compile_script = "gcc /var/www/FilebCamFz.c -o /var/www/FilebCamFz";
FILE *output_file;
output_file = popen(compile_script, "w");

char *output, *full_output, *full_error;
output = malloc(50000);
full_output = malloc(50000);
full_error = malloc(50000);

setbuf(stderr, full_error);
setbuf(stdout, full_output);

if(output_file == NULL){
    // Some error
    fprintf(stderr, "Compilation failed. Try again.\n");
    return full_error;
}
else{
    // If command executed successfully
    while (fgets(output, 5000000, output_file) != NULL){
       strcat(full_output, output);
    }

    if (pclose (output_file) == 0){
        return full_output;
    }
    else
        fprintf (stderr, "Could not run more or other error.\n");
        return full_error;
}

//return EXIT_SUCCESS; }

使用lsfree -m 命令调用函数时,输出如预期。

但是当运行python -v等命令时,会得到一个空的输出。

在运行gcc /var/www/FilebCamFz.c -o /var/www/FilebCamFz 之类的命令时,我在pclose() 上得到了一个标准错误。

所以我的问题是,popen 这种不寻常的行为的原因是什么。 以及如何通过popen() 编译外部程序(c、c++、python、java 等)

【问题讨论】:

  • “pclose() 上的标准错误”?嗯? stderr 是文件描述符,而不是错误号。
  • 您似乎也对setbuf 的作用感到困惑。
  • 我还应该指出,这似乎很幼稚并且可能非常脆弱。我会在编译和执行其他人的代码时阅读some of the lengths that codepad.org goes to
  • 那么执行此类命令的最佳方式是什么。我已经忽略了受限调用和系统资源。
  • 您应该使用fread 而不是fgets 来处理二进制数据,否则每次遇到0xa(例如'\n' 字符)时,您的读取都会终止。

标签: c linux popen


【解决方案1】:

我们终于通过使用 docker 容器解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2015-02-21
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多