C++ popen 运行 PHP
我正在使用 http://www.jukie.net/bart/blog/popenRWE 并在使用 cat
命令时编写下面的脚本
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
直接在控制台运行 ,并得到输出。有人可以就这段代码提供建议或帮助吗?提前致谢。
i'm using popenRWE from http://www.jukie.net/bart/blog/popenRWE and making the script below
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;
when i use cat
command, it works, the input is the ouput (that's what cat doing), but using php
the read is empty. i have confirmed that php is installed and on my path by running
echo "<?php echo 'hello world';?>" | php
directly on the console, and got the output. Can someone please advise or help on this code? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码存在三个问题:
"php "
的可执行文件。只有"php"
(请注意,没有空格)。这不起作用的原因是因为popenRWE
使用execvp
它不会启动 shell 来执行命令,但它需要您要执行的二进制文件的文件名(但它会在$PATH
中搜索它)。关闭
stdin 文件句柄,否则您可能需要无限期地等待输出写入。waitpid
等待php
进程完成,否则您可能会“丢失”一些输出。总结一下:
There are three problems with your code:
"php "
. There is just"php"
(notice that there is no space). The reason why this does not work is beceausepopenRWE
usesexecvp
which does not start a shell to execute the command but it expects the filename of the binary you want to executed (it searches for it in$PATH
though).close
thestdin
-filehandle after you've written your data, otherwise you might have to wait indefinitely for the output to be written.php
-process to finish usingwaitpid
because otherwise you might "lose" some of the output.To wrap it up: