简体   繁体   English

在php中重复运行外部程序

[英]Run external program in php repetitive

I want to run a program written with c++ in web server repetitive. 我想在Web服务器中重复运行用C ++编写的程序。 Because there is something that php can't do, but c++ can do it easy. 因为有些事情是php无法做到的,但是c ++却可以做到这一点。

I searched and found that it could be done by using exec function in php. 我搜索并发现可以通过使用php中的exec函数来完成。

I used this in js setInterval to run that program every 100ms. 我在js setInterval使用了它,以便每100毫秒运行一次该程序。 But it seems that that program runs when web page loads and in js code, I have the same output. 但是似乎该程序在网页加载时运行,并且在js代码中,我具有相同的输出。

for example, when I want to get current date from c++ program. 例如,当我想从c ++程序获取当前日期时。 the cpp code is: cpp代码为:

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
    time_t now = time(0);
    tm *ltm = localtime(&now);
    cout << 1 + ltm->tm_sec;
    return 0;
}

and in index.php file I used this for print current second at page every 100ms. index.php文件中,我将其用于每100毫秒在页面上打印第二秒。

<script>
    setInterval(function(){
        var date = "<?php passthru("print_date.exe"); ?>";
        document.write(date + "<br>");
    },100);
</script>

but it prints always the same! 但是它打印的总是一样的!

Is there any other way to do this? 还有其他方法吗? Thanks! 谢谢!

Because php code is executed only 1 time. 因为php代码仅执行1次。 Use Ajax as an option. 使用Ajax作为选项。

//updated next day. //第二天更新。 1. file (index.php) 1.文件(index.php)

<script>
var aj;

setInterval(function()
{
aj = new XMLHttpRequest();
aj.open('GET',"/print_date.php",false);
aj.onreadystatechange  = processData;
aj.send(null);
},1000);

function processData()
{
var date = '';
if (aj.readyState == 4) 
{
date = aj.responseText;
document.write(date + "<br>")   
}
}
</script>

It is very simple synchronous ajax. 这是非常简单的同步ajax。 interval is 1000, not 100, because 1000ms = 1s (C++ program returns time in seconds!). 间隔是1000,而不是100,因为1000ms = 1s(C ++程序以秒为单位返回时间!)。

2) So, print_date.php is 2)所以,print_date.php是

<?php 
 error_reporting(0); //because any warning destroys output for ajax
 passthru("print_date.exe"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM