0

been trying to figure this one out for a couple of hours now. No luck.

I am trying to build a system that can run reports (running scripts in the background) using shell_exec.

The following code starts the script that runs the report: shell_exec("php /var/www/html/lab-40/test/invoice_reminder.php");

Now how would I go about ending that script execution using PHP?

I've tried things like PIDS but I have no clue how I would go about this. Thanks for the help in advance!

EDIT: I am not trying to end the process if the e.g tab is closed.

user3724476
  • 4,720
  • 3
  • 15
  • 20
  • Out of curiosity, why do you want to force end it? – Furgas Feb 04 '19 at 11:31
  • So from a web-based control panel, lets say the user wants to cancel running the report – user3724476 Feb 04 '19 at 11:32
  • Check out this [comment](http://php.net/manual/en/function.shell-exec.php#59898) on `shell_exec` help page. – Furgas Feb 04 '19 at 11:37
  • Possible duplicate of [PHP shell\_exec - how to terminate the process if the connection is closed?](https://stackoverflow.com/a/16103650/10967889) – weegee Feb 04 '19 at 11:41
  • @daksh I don't want the script to be killed upon the tab being closed. – user3724476 Feb 04 '19 at 11:43
  • @user3724476 `shell_exec('kill -KILL ProcessID');` this might help – weegee Feb 04 '19 at 11:44
  • @Furgas Thanks for that. With actually getting the PID I assume it's this part of the shell_exec that gets it "& echo $!". – user3724476 Feb 04 '19 at 11:44
  • For better control of child processes, take a look át [PCNTL Functions](http://php.net/manual/en/ref.pcntl.php) and [POSIX Functions](http://php.net/manual/en/ref.posix.php). – Wiimm Feb 04 '19 at 12:07

1 Answers1

2

Based on this comment on shell_exec help page (& will bring the process to the background, and echo $! will print the process PID):

<?php

function shell_exec_background(string $command): int {
    return (int)shell_exec(
        sprintf(
            'nohup %s 1> /dev/null 2> /dev/null & echo $!',
            $command
        )
    );
}

function is_pid_running(int $pid): bool {
    exec(
        sprintf(
            'kill -0 %d 1> /dev/null 2> /dev/null',
            $pid
        ),
        $output,
        $exit_code
    );

    return $exit_code === 0;
}

function kill_pid(int $pid): bool {
    exec(
        sprintf(
            'kill -KILL %d 1> /dev/null 2> /dev/null',
            $pid
        ),
        $output,
        $exit_code
    );

    return $exit_code === 0;
}

$pid = shell_exec_background('php /var/www/html/lab-40/test/invoice_reminder.php');
var_dump($pid);
var_dump(is_pid_running($pid));
var_dump(kill_pid($pid));
Furgas
  • 2,729
  • 1
  • 18
  • 27