Skip to content
Advertisement

PHP kill exec() background process after php-fpm restarted

I use nginx and php7.1-fpm. I want to run a background process using PHP and exec().

My short code:

<?php
exec('/usr/local/bin/program > /dev/null 2>&1');

Unfortunately after the systemd restart php7.1-fpm the program is killed.

I have tried to run with a different user than the one running the pool:

<?php
exec('sudo -u another_user /usr/local/bin/program > /dev/null 2>&1');

However, this does not solve the problem – still kills.

I can not use ssh2_connect(). How can I solve this problem?

Advertisement

Answer

It seems this is due to the php-fpm service being managed by the systemd.

All processes launched from php-fpm belong to its control-group and when you restart the service systemd sends the SIGTERM to all the processes in the control-group even if they are daemonized, detached and/or belong to another session.

You can check your control-groups with this command:

systemd-cgls

What I’ve done is to change the KillMode of the php-fpm service to process. Just edit it’s .service file:

vi /etc/systemd/system/multi-user.target.wants/php7.0-fpm.service

and change or add the line to the [Service] block:

KillMode=process

Then reload the configuration by executing:

systemctl daemon-reload

That worked for me.

References: Can’t detach child process when main process is started from systemd

http://man7.org/linux/man-pages/man5/systemd.kill.5.html

What would be wonderful would be a command (similar to setsid) that allowed to launch a process and detach from control-group but I haven’t been able to find it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement