PHP on a windows machine; Start process in background

后端 未结 5 1328
无人及你
无人及你 2020-12-10 06:46

I\'m looking for the best, or any way really to start a process from php in the background so I can kill it later in the script.

Right now, I\'m using: shell_exec($C

相关标签:
5条回答
  • 2020-12-10 07:09

    shell_exec('start /B "C:\Path\to\program.exe"');

    The /B parameter is key here.

    I can't seem to find where I found this anymore. But this works for me.

    0 讨论(0)
  • 2020-12-10 07:13

    From the php manual for exec:

    If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

    ie pipe the output into a file and php won't wait for it:

    exec('myprog > output.txt');
    

    From memory, I believe there is a control character that you can prepend (like you do with @) to the exec family of commands that also prevents execution from pausing - can't remember what it is though.

    Edit Found it! On unix, programs executed with & prepended will run in the background. Sorry, doesn't help you much.

    0 讨论(0)
  • 2020-12-10 07:14

    Tried to achieve the same on a Windows 2000 server with PHP 5.2.8.

    None of the solutions worked for me. PHP kept waiting for the response.

    Found the solution to be :

    $cmd = "E:\PHP_folder_path\php.exe E:\some_folder_path\backgroundProcess.php";
    pclose(popen("start /B ". $cmd, "a"));  // mode = "a" since I had some logs to edit
    
    0 讨论(0)
  • 2020-12-10 07:22

    On my Windows 10 and Windows Server 2012 machines, the only solution that worked reliably within pclose/popen was to invoke powershell's Start-Process command, as in:

    pclose(popen('powershell.exe "Start-Process foo.bat -WindowStyle Hidden"','r'));
    

    Or more verbosely if you want to supply arguments and redirect outputs:

    pclose(popen('powershell.exe "Start-Process foo.bat 
                 -ArgumentList \'bar\',\'bat\' 
                 -WindowStyle Hidden
                 -RedirectStandardOutput \'.\\console.out\' 
                 -RedirectStandardError \'.\\console.err\'"','r'));
    
    0 讨论(0)
  • 2020-12-10 07:34

    Will this function from the PHP Manual help?

    function runAsynchronously($path,$arguments) {
        $WshShell = new COM("WScript.Shell");
        $oShellLink = $WshShell->CreateShortcut("temp.lnk");
        $oShellLink->TargetPath = $path;
        $oShellLink->Arguments = $arguments;
        $oShellLink->WorkingDirectory = dirname($path);
        $oShellLink->WindowStyle = 1;
        $oShellLink->Save();
        $oExec = $WshShell->Run("temp.lnk", 7, false);
        unset($WshShell,$oShellLink,$oExec);
        unlink("temp.lnk");
    }
    
    0 讨论(0)
提交回复
热议问题