繁体   English   中英

Popen和execl没有给出用户定义程序的输出

[英]Popen and execl not giving the output of the user defined program

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

popen示例:

#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;
}

php的例子

#!/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

任何帮助都将非常感谢! 谢谢!

您需要在使用时要执行PHP解释器,并通过脚本作为参数的名称, popen如果你的脚本没有家当因为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不使用shell:

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

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

fread(buf, 1, 1024, pipe);

暂无
暂无

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

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