1 2 下一页 我近期做一个东东,大致构架是: 访问者通过Web提交c程序,服务端调用编译器编译并且在编译完成后运行编译后的程序,将运行结果传回访问者浏览器。 且不考虑安全性,因为访问者可以都认为是可以信赖的,命令行编译器最终要返回的,但是对于临时编译的程序,尽管用户是可以信赖的,但是不排除因为不完善而出现死锁,PHP调用后启动的进程无法返回而超时,此进程一直存在直到服务器重启,久而久之,服务器端资源就要耗尽。 考虑到php本身执行的时候没有提供多线程和进程管理功能(可能是我没有看到这方面的资料),使用不管是exec,还是popen等,主程序一旦阻塞就无法自拔,所以必须预留一个线程在必要时管理启动的进程.而我又不想对服务器配置做改动。于是想到自己写一个程序管理启动的进程,php间接通过这个程序调用编译后的客户程序,实现对客户程序超时的控制。 下面是测试用的php程序。 <? //filename: test1.php $cmd="test.exe 24 154";// input you command here $cmd="process.exe 5000 ".$cmd; $descriptorspec = array( 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 2 => array("file", "error-output.txt", "w+"), // stderr is a file to write to ); $process = proc_open($cmd, $descriptorspec, $pipes); if (is_resource($process)) { // $pipes now looks like this: // 0 => writeable handle connected to child stdin // 1 => readable handle connected to child stdout // Any error output will be appended to /tmp/error-output.txt fwrite($pipes[0], '12345678');// input integer to scanf, you should add 'n' at the end of string as 'Enter'; fclose($pipes[0]); while(!feof($pipes[1])) { echo nl2br(fgets($pipes[1], 1024)); } fclose($pipes[1]); // It is important that you close any pipes before calling // proc_close in order to avoid a deadlock //proc_terminate($process); $return_value = proc_close($process); echo "<br>command returned $return_valuen"; } ?>
(责任编辑:admin) |