Pregunta

I'm running a linux command through PHP passthru(), example:

<?php
file_put_contents("script.pid", getmypid());
passthru("sleep 500", $exit);

Now say I want to kill the script. I would kill the process listed in script.pid; however, this leaves the sleep 500 (or any process) running in the background. I get the same result from system() and shell_exec() although I am using passthru() for the exit return variable. Anyone know a solution or even a reason of why this leaves the process running in the background?

¿Fue útil?

Solución

Function passthru() spawns a shell to run your command and then blocks until the passthru process returns. Those are independent processes with different Process IDs than the php interpreter running your script. You can kill the script but you won't kill the processes it started.

However the spawned processes have the same Process Group ID (PGID) and you can use that to kill them or sent them any other signal. The PGID in our case would be the same as the Process ID (PID) of the php script.

To see the PGIDs you can execute the command: ps axjf and you will get something like:

PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
24077 12484 12484 24077 pts/9    12484 S+    1000   0:00  |   \_ php sleepScript.php
12484 12486 12484 24077 pts/9    12484 S+    1000   0:00  |       \_ sh -c sleep 500
12486 12487 12484 24077 pts/9    12484 S+    1000   0:00  |           \_ sleep 500

the PGID in our example is 12484 (same as the PID of the php script) and to send to that group a terminate signal, use the kill command with a negative sign in front of the PGID, i.e.:

kill -15 -24077

and you will have terminated all three processes.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top