简体   繁体   中英

How to get pid of the process that run in background exec by shell in php

I'm working on a shell in php, and I want to display the same output as bash. When in bash you execute sleep 10 & you'll get [1] <PID> . How can I do the same in php, when I call shell using:

    if (preg_match("/&\s*$/", $command)) {
        $this->$shell_fn($token, '/bin/bash -c ' . escapeshellarg($command) .
                         " > /dev/null");
        return array(
            'output' => '',
            'cwd' => $path
        );
    }

$shell_fn is variable that point to wrapper over shell_exec, exec or cgi script called by curl. Is it even possible to get the pid from php or using a shell?

If you want the pid in , you can do use the ! special parameter to get the pid of the most recently backgrounded process:

bash -c 'sleep 10 & echo $!'

I don't know exactly how spawns external processes, but I imagine you'd be able to capture the echo output here, just by running the above shell command.

I use this functions to manage process:

function ProcessStart($cmdline) // return pid
{
    exec( "nohup $cmdline >/dev/null 2>&1 & echo $!", $output) ;
    // print_r ($output);
    return (int)$output[0];
}

function ProcessStatus($pid) // return TRUE (live) o FALSE (dead)
{
    exec("ps -p $pid",$output);
    // print_r($output);
    return ( isset($output[1]) ? TRUE : FALSE ) ;
}

function ProcessStop($pid)
{
    exec("kill $pid",$output); // kill -9 ??
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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