0

我正在尝试在我的 C 程序中执行其他程序。我的第一次尝试是使用 popen。当我尝试从中读取时,pipe我只得到 1 个字节的回复,而在 buf 中什么也没有。我不确定这背后的原因。

弹出示例:

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

int main(int argc, char* argv[])
{
        FILE* pipe;
        if ((pipe=(FILE*)popen("./test.php","r"))==NULL)
                printf("this is not working\n");
        char buf[1024] = {'\0'};

        int fd=fileno(pipe);

        int bytes = read(fd, buf, 1024);

        printf("bytes read %d\n", bytes);

        printf("The program: %s\n", buf);
        if(pclose(pipe)<0)
                printf("not working\n");
        return 0;
}

例子

#!/usr/bin/php

<?php
echo "THIS IS A TEST THAT WORKED\n";
?>

输出:

bytes read 1
The program:

ls的输出:

ls -l test.php
-rwxr-xr-x+ 1 tpar44 user 62 Nov 10 14:42 test.php

对此的任何帮助将不胜感激!谢谢!

4

1 回答 1

2

popen如果您的脚本没有shebang ,则需要执行php解释器并将脚本的名称作为参数传递,因为shell不知道要使用哪个解释器:

fp = popen("php /path/to/script/test.php", "r");

如果脚本有 shebang 行,你可以直接执行它,因为popen使用 shell 来执行命令,它可以找出要使用的命令,所以你可以这样做:

 fp = popen("/path/to/script/test.php", "r");

但是,请确保脚本是可执行的:

chmod +x test.php

您也可以使用execl(),但您必须指定二进制文件的路径,因为execl不使用外壳:

execl("/usr/bin/php", "/usr/bin/php", "-q",
      "/path/to/script/test.php", (char *) NULL);

不要忘记从管道中实际读取;)

fread(buf, 1, 1024, pipe);
于 2012-11-10T19:08:18.640 回答