求解php和c语言的进程间通信能兼容吗
1个回答
展开全部
PHP是比较流行的脚本语言,WEB开发使用广泛,如何在C++程序中不依赖任何WEB SERVER调用PHP,并取得执行结果完成交互。
PHP安装好后,在目录下有一个php-cgi.exe,我们只要执行这个CGI程序,并将数据通过命名管道传递给它,然后把执行结果通过命名管道读取出来即可,过程并不复杂!请看如下代码:
命名管道的创建:
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES)};
sa.bInheritHandle = 1;
sa.lpSecurityDescriptor = NULL;
HANDLE hStdoutR, hStdoutW, hStdinR, hStdinW;
CreatePipe(&hStdoutR, &hStdoutW, &sa, 0);
SetHandleInformation(hStdoutR,HANDLE_FLAG_INHERIT, 0);
CreatePipe(&hStdinR, &hStdinW, &sa, 0);
SetHandleInformation(hStdinW, HANDLE_FLAG_INHERIT, 0);
启动php-cgi进程: STARTUPINFO si = {sizeof(STARTUPINFO)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutW;
si.hStdInput = hStdinR;
char env[255] = "REQUEST_METHOD=POST\0CONTENT_LENGTH=18\0CONTENT_TYPE=
application/x-www-form-urlencoded\0SCRIPT_FILENAME=D:\\test.php";
if(!CreateProcess(NULL, "d:\\php5\\php-cgi.exe D:\\test.php",
NULL, NULL, 1, NORMAL_PRIORITY_CLASS, env, NULL, &si, &pi))
return 0;
CloseHandle(hStdoutW);
CloseHandle(hStdinR);
传递数据:if(!WriteFile(hStdinW, "var=Hello VCKBASE!", 18, &dwWritten, NULL))
return 0;
CloseHandle(hStdinW);
读取返回数据:char buf[1000] = {0};
DWORD dwRead = 0;
while(ReadFile(hStdoutR, buf, sizeof(buf), &dwRead, NULL) && dwRead != 0){
printf(buf);
}
CloseHandle(hStdoutR);
D盘的test.php
<?
echo $_REQUEST["var"];
?>
执行结果:
X-Powered-By: PHP/5.3.1
Content-type: text/html
Hello VCKBASE!
实际上,C++调用其他CGI程序,例如PERL,方法也大同小异,如果你打算做一个自己的WEB服务器,调用CGI程序是少不了的。
PHP安装好后,在目录下有一个php-cgi.exe,我们只要执行这个CGI程序,并将数据通过命名管道传递给它,然后把执行结果通过命名管道读取出来即可,过程并不复杂!请看如下代码:
命名管道的创建:
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES)};
sa.bInheritHandle = 1;
sa.lpSecurityDescriptor = NULL;
HANDLE hStdoutR, hStdoutW, hStdinR, hStdinW;
CreatePipe(&hStdoutR, &hStdoutW, &sa, 0);
SetHandleInformation(hStdoutR,HANDLE_FLAG_INHERIT, 0);
CreatePipe(&hStdinR, &hStdinW, &sa, 0);
SetHandleInformation(hStdinW, HANDLE_FLAG_INHERIT, 0);
启动php-cgi进程: STARTUPINFO si = {sizeof(STARTUPINFO)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutW;
si.hStdInput = hStdinR;
char env[255] = "REQUEST_METHOD=POST\0CONTENT_LENGTH=18\0CONTENT_TYPE=
application/x-www-form-urlencoded\0SCRIPT_FILENAME=D:\\test.php";
if(!CreateProcess(NULL, "d:\\php5\\php-cgi.exe D:\\test.php",
NULL, NULL, 1, NORMAL_PRIORITY_CLASS, env, NULL, &si, &pi))
return 0;
CloseHandle(hStdoutW);
CloseHandle(hStdinR);
传递数据:if(!WriteFile(hStdinW, "var=Hello VCKBASE!", 18, &dwWritten, NULL))
return 0;
CloseHandle(hStdinW);
读取返回数据:char buf[1000] = {0};
DWORD dwRead = 0;
while(ReadFile(hStdoutR, buf, sizeof(buf), &dwRead, NULL) && dwRead != 0){
printf(buf);
}
CloseHandle(hStdoutR);
D盘的test.php
<?
echo $_REQUEST["var"];
?>
执行结果:
X-Powered-By: PHP/5.3.1
Content-type: text/html
Hello VCKBASE!
实际上,C++调用其他CGI程序,例如PERL,方法也大同小异,如果你打算做一个自己的WEB服务器,调用CGI程序是少不了的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询