gpt4 book ai didi

java - 使用PHP exec命令打破无限循环java程序

转载 作者:行者123 更新时间:2023-11-30 02:57:59 25 4
gpt4 key购买 nike

我有 JDK,我正在尝试执行包含无限循环的 Main.java 程序,并且我想在 java Main.java < input.txt > output.txt 命令进入无限循环时中断它,如果不是的话无限循环不会破坏程序..有什么解决方案吗?遇到麻烦了

<?php

exec('cmd /k c:/wamp/www/javac Main.java 2>&1', $outputAndErrors, $return_value);
for($i=0 ; $i<sizeof($outputAndErrors) ; $i++)
{
$output1=htmlspecialchars($outputAndErrors[$i],ENT_QUOTES);
echo "$output1";
$flag=1;
}
if(!$flag)
{
exec('cmd /k c:/wamp/www/java Main.java < input.txt > output.txt', $outputAndErrors, $return_value);
//want to give timeout but if exec goes to infinite loop than below statement will not executed
}

?>

最佳答案

尝试将其包装在这样的类中(本质上是将其包装在 nohup COMMAND >/dev/null 2>&1 & echo $! 中以获取 pid 并在后台以这种方式使用它)

<?php
// You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
$process = new Process('ls -al');

// or if you got the pid, however here only the status() metod will work.
$process = new Process();
$process.setPid(my_pid);
?>

<?php
// Then you can start/stop/ check status of the job.
$process.stop();
$process.start();
if ($process.status()){
echo "The process is currently running";
}else{
echo "The process is not running.";
}
?>

<?php
/* An easy way to keep in track of external processes.
* Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
* @compability: Linux only. (Windows does not work).
* @author: Peec
*/
class Process{
private $pid;
private $command;

public function __construct($cl=false){
if ($cl != false){
$this->command = $cl;
$this->runCom();
}
}
private function runCom(){
$command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
exec($command ,$op);
$this->pid = (int)$op[0];
}

public function setPid($pid){
$this->pid = $pid;
}

public function getPid(){
return $this->pid;
}

public function status(){
$command = 'ps -p '.$this->pid;
exec($command,$op);
if (!isset($op[1]))return false;
else return true;
}

public function start(){
if ($this->command != '')$this->runCom();
else return true;
}

public function stop(){
$command = 'kill '.$this->pid;
exec($command);
if ($this->status() == false)return true;
else return false;
}
}
?>

关于java - 使用PHP exec命令打破无限循环java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36725654/

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