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,189
  • 3
  • 13
  • 18

2 Answers2

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,692
  • 1
  • 17
  • 26
-1

For better control of child processes, take a look át PCNTL Functions and POSIX Functions.

Wiimm
  • 2,430
  • 1
  • 13
  • 22