0

I would like to run a background process, which is orphaned, with Symfony Process component. I can't use kernel.terminate event. This is what I have tried to do:

This is process I would like to run:

// script.php
$f = fopen('test'.uniqid().'.txt', 'w');
for ($i = 0; $i < 1000; $i++) {
    fwrite($f, "Line $i \n");
    sleep(2);
}
fclose ($f);

And this is script which I would like to run my process:

// test.php
$command = "php script.php > /dev/null 2>&1 &";

$p = new \Symfony\Component\Process\Process($command);
$p->start();
echo $p->getPid()."\n";

The problem is that after test.php termination, script.php is not working. Termination of main script kills all subprocesses. Is it possible to have orphaned processes running with Symfony Process?

michail_w
  • 4,318
  • 4
  • 26
  • 43

2 Answers2

1

Easiest way, don't use the Process Component and fall back to php exec:

http://php.net/manual/de/function.exec.php

exec('php script.php > /dev/null 2>&1 &');

For a more solid solution consider something like a schedule and a crontab executed command to start the process when one needs to be started.

Joe
  • 2,356
  • 10
  • 15
  • I'm fairly certain this will do the same thing as the OP is already doing. – Jonathan Apr 05 '17 at 15:49
  • 2
    It is not. Process component uses proc_open which actually returns a resource for the output which is monitored by the Process component. exec works different it's fire and forget (given the last `&` at the end of the executed command) – Joe Apr 05 '17 at 15:54
  • Process lib is bloated and useless. Lost a lot of time playing with it and ended up with old good exec(). – ymakux Aug 16 '20 at 11:38
0

You can use at (atd) or cron with a custom queue. PHP invokes synchronous command which enqueues the desired command for later execution. The at is quite powerful and standard component of unix systems. You simply run at now + 10 min and push commands to its stdin, then the atd daemon will run your commands in 10 minutes.

If you wish to run your command directly from PHP, try to add shell: new Process('/bin/sh -c "php script.php &"'). I'm not sure how exactly Process class invokes the command, but if & does not work, one more shell in between will do the trick (that is what exec() does).

Josef Kufner
  • 2,851
  • 22
  • 28