访问Symfony2中的后台进程

I would like to create a background process in Symfony2, using the Process component and run it in background, like this:

$process = new Process('php myfile.php --option1 --option2');
$process->start();

The script which I want to run here would run indefinetely (while (true) or something like that) and should be possible to kill from a console command or from a controller.

The question is - how can I access such a process in Symfony (e.g. from a controller) from a different context than it was created? That is - without the original Process instance? Let's say a request to a route create_process starts the process, then a request to kill_process should kill it. Is it even possible?

One way I can think of is serializing the process object and storing in in the database but it seems there could be lots of problems with this solution.

You shouldn't do this.

PHP is stateless, each Request is completely unique.

I don't know how Symfony Processes work internally, but AFAIK there is no way to kill commands executed through exec(),passthru() or the like.

You could read this section and find out if it helps: http://symfony.com/doc/current/components/process.html#process-pid

If it doesn't you could still get the current timestamp (e.g. 1422971460) when you start the process, and periodically check for the existence of a file called "kill_1422971460", and as soon as it exists, delete it and end the process.

But I would advise you to use another programming language for this kind of processes, as PHP is not designed for this. Also you can hit max_execution_time or timeouts between apache and fcgi threads, which will end up killing your process. It's not reliable and it won't serve you well.

I've done something like this using the DaemonizableCommandBundle:

It has a EndlessCommand class that you can extend and create a command that does something in a loop, and which you could terminate anytime; it does try to terminate the iteration gracefully.