gpt4 book ai didi

php - C++ popen 运行 PHP

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:53 26 4
gpt4 key购买 nike

我正在使用来自 http://www.jukie.net/bart/blog/popenRWE 的 popenRWE并制作下面的脚本

int pipes[3];
int pid;
const char *const args[] = {
"php ",
NULL
};
pid = popenRWE(pipes, args[0], args);

char *cmd = "<?php echo 'hello world';?> ";
cout << "write: " << write(pipes[0], cmd, strlen(cmd)) << endl;
cout << "err: " << errno << endl;

char res[100];
cout << "read: " << read(pipes[1], res, 100) << endl;
cout << "result: " << res << endl;

当我使用 cat 时命令,它有效,输入就是输出(这就是猫所做的),但使用 php读取为空。我已经通过运行确认 php 已安装并且在我的路径上

echo "<?php echo 'hello world';?>" | php

直接在控制台上,得到了输出。有人可以就此代码提供建议或帮助吗?提前致谢。

最佳答案

您的代码存在三个问题:

  • 没有名为"php " 的可执行文件。只有 "php"(注意没有空格)。这不起作用的原因是因为 popenRWE 使用 execvp它不会启动 shell 来执行命令,但它需要您要执行的二进制文件的文件名(尽管它会在 $PATH 中搜索它)。
  • 您应该在写入数据后关闭 stdin-filehandle,否则您可能不得不无限期地等待输出被写入。
  • 您还应该等待 php 进程使用 waitpid 完成,否则您可能会“丢失”一些输出。

总结一下:

int pipes[3];
int pid;
const char *const args[] = {
"php",
NULL
};
pid = popenRWE(pipes, args[0], args);

char *cmd = "<?php echo 'hello world', \"\\n\";?> ";
cout << "write: " << write(pipes[0], cmd, strlen(cmd)) << endl;
cout << "err: " << errno << endl;
close(pipes[0]);

// TODO: proper error handling
int status;
waitpid(pid, &status, 0);

char res[100];
int bytesRead = read(pipes[1], res, (sizeof(res)/sizeof(char))-1);
// zero terminate the string
res[bytesRead >= 0 ? bytesRead : 0] = '\0';

cout << "read: " << bytesRead << endl;
cout << "result: " << res << endl;

关于php - C++ popen 运行 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7884782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com