【问题标题】:Execute and output PHP on a C based web-server - Stuck!在基于 C 的 Web 服务器上执行和输出 PHP - 卡住了!
【发布时间】:2011-01-11 21:01:19
【问题描述】:

我正在为大学做一些课程作业,但我完全感到困惑。基本上我已经用 C 语言制作了一个基本的 Web 服务器(它使用套接字)。我现在必须制作它,以便任何 .php 文件都可以通过 php 编译器运行并输出。

我遇到的问题是我尝试过使用 system() 和 execlp()(后者是我们的讲师推荐的),但不知道如何让它显示在页面而不是终端上。

这是显示我目前获得的代码的摘录。请原谅所有的 cmets...如您所见,我一直在尝试各种方法来让它工作!

代码:

if(strncmp(resource, ".php", 4)==1) {
 //cout << "test";

int php;

  int phppipefds[2], phppid;
  char phpc;
  pipe(phppipefds);
  phppid = fork();
  if(phppid == 0) { // child will read pipe 
 close(0); // close stdin
 dup2(phppipefds[0],0); // read pipe on stdin
 close(phppipefds[1]); // we dont need to write pipe
 execlp("/Applications/MAMP/bin/php5/bin/php", "php", httppath, NULL); 
 cerr << "exec failed\n"; 
 exit(1);
}
// parent, if we redirect stdout printf will send down pipe 
close(1); 
dup2(phppipefds[1],1); // write pipe on stdout
close(phppipefds[1]); // dont need 2 write descriptors
close(phppipefds[0]); // we dont need to read pipe
cout << "words \ngoing \ndown \npipe \nbeing \nsorted\n"; 
close(1); // must close pipe or sort will hang
wait(0);

//php = system("/Applications/MAMP/bin/php5/bin/php /Users/rickymills/webserver/pages/test.php");
//strcat(resp, );
//strcat(resp, php);
 }

最后几行是我一直在尝试各种方法让这个东西工作的地方。

将所有内容转储到浏览器窗口的实际部分就在上述代码的下方:

 write(connsock, resp, rd);
 exit(1);
} 

有没有人知道我怎样才能把它放到浏览器窗口中?我原以为最好的方法是将 php 输出放入一个变量中,并在 connsock 写出之前将其与 'resp' 结合起来,这是正确的吗?

感谢您的宝贵时间。

【问题讨论】:

    标签: php c http unix sockets


    【解决方案1】:

    尝试使用 popen() 代替 system() 或 execlp()。

    popen() 函数通过创建管道、分叉和​​调用 shell 来打开一个进程。这应该允许您将 PHP 输出重定向回您的程序而不是终端。

    char buf[BUFSIZ];
    FILE *fp;
    
    if ((fp= popen("/bin/php -f /webserver/pages/test.php", "r")) != NULL)
    {
        /* Read from the PHP command output */ 
        while (fgets(buf, BUFSIZ, fp) != NULL)
        {
            /* Process the output from PHP as desired */
            ...
        } 
    
        (void) pclose(ptr);
    }
    
    fclose(fp);
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多