Reputation: 117
So I have this code where I execute a c++ program. $out
simply contains the output of the program.
$cmd = "c:/Server/www/Codice/LOGS/".$_SESSION['username']."/chorva.exe";
$out = shell_exec($cmd);
echo $out;
And that works. However, I want to terminate the program after a few seconds, say after 6-10 seconds. (This is equivalent to Ctrl-C
when you are in a terminal.) This is so if the program executes too long (or endlessly e.g. infinite loops), it doesn't have to wait. I am also concerned with the output it produces in that time (if that's even possible). How can I do this? Thanks!
Upvotes: 2
Views: 610
Reputation: 225
In Windows PHP there doesn't seem to be a way of running a program asynchronously AND reading its output AND killing it after a certain period, so I would like to recommend using an external program to do it.
I don't know if any such program already exists, but you can always create your own. And supposing you want to stick to scripting languages, here's an example of such program on VBScript
Dim WshShell, objFSO, oExec, cmd, wait, tempFile, objFile
Set WshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
wait = WScript.Arguments(0)
cmd = WScript.Arguments(1)
tempFile = objFSO.GetTempName()
Set oExec = WshShell.Exec(cmd & " > " & tempFile)
Do While oExec.Status <> 1
WScript.Sleep 100
wait = wait - 100
If wait <= 0 Then Exit Do
Loop
oExec.Terminate()
Const ForReading = 1
Set objFile = objFSO.OpenTextFile(tempFile, ForReading)
Do While objFile.AtEndOfStream = False
Wscript.Echo(objFile.ReadLine())
Loop
objFile.Close()
objFSO.DeleteFile(tempFile)
The script runs a program cmd
, waits until it's dead in 100 millisecond ticks, and if it doesn't die in wait
milliseconds, kills it. The program output is saved into a temporary file, which is read and echoed.
wait
and cmd
are first and second script arguments. The script is run as
cscript //Nologo runcmd.vbs <time> <cmd>
Upvotes: 1