0

When I manually run this command via SSH:

xx@xxx.com [~/public_html/xxx]# ls > ls2.out 2>&1 &
[1] 15205

Which simply returns the PID of the background process which in this case is 15205. However when I tried to do the same via PHP code:

$run = "ls > ls2.out 2>&1 &";
$return = exec($run, $output, $return_var);
echo '=====', PHP_EOL;
echo var_dump($run);
echo var_dump($return);
echo print_r($output);
echo print_r($return_var);
echo '=====', PHP_EOL;

It doesn't return the PID but just an empty string:

=====
string(19) "ls > ls2.out 2>&1 &"
string(0) ""
Array
(
)
101=====

Why?

How can I get the PID of the background process via PHP exec()?

datasn.io
  • 12,564
  • 28
  • 113
  • 154
  • http://stackoverflow.com/questions/38975328/php-get-pid-of-process-and-kill-it – samayo Jan 16 '17 at 15:15
  • @samayo Adding ' echo $!; ' to the end of the command as "ls > ls2.out 2>&1 & echo $!; " worked. However, is the & ampersand used as a command connector or as putting to background here? Is the command put to background at all in this case? – datasn.io Jan 16 '17 at 15:19
  • Yes, I believe so... I can't try it now, also I use screen/nohup but you should be fine – samayo Jan 16 '17 at 15:25

1 Answers1

1

use the proc_open for subprocess, and proc-get-status to get the pid. for exec refer to this post.

<?php
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")
    );
    $command = 'ping -c 10 stackoverflow.com';

    $process = proc_open($command, $descriptorspec, $pipes);
    echo 'hahaha';
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
LF00
  • 27,015
  • 29
  • 156
  • 295
  • Does proc_open() also work to put the process to background? We are running processes that would last hours and even days. Is it OK with proc_open()? – datasn.io Jan 16 '17 at 15:22
  • certainly, and it have more function. – LF00 Jan 16 '17 at 15:27
  • but it seems to be mandatory to proc_close() the process before the PHP script ends or it will be a deadlock. However what I want is start a process in the background which keeps running even if my PHP script ends. Do I still need to proc_close() it explicitly? – datasn.io Jan 17 '17 at 03:25
  • @kavoir.com I've add a test code, you can make it a file test.php then test it with php test.php. – LF00 Jan 17 '17 at 04:34