Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a daemon with php

Tags:

linux

php

daemon

I want to be able to stop/start a daemon (on Debian) by clicking a button on a website. I know the daemon works, because via SSH it does start and stop. I can even capture the status with

$status = exec("/etc/init.d/MyService.sh status | grep 'is running'");

But this doesn't work:

exec('/etc/init.d/MyService.sh start', $output);

There I get this error: Starting system MyService daemon: failed! I guess it has to do with permissions but I don't know how. The permissions of the .pid file is -rwxrw-rw-

I read this https://stackoverflow.com/a/6720364/3486924 and this Starting a daemon from PHP but both didn't help either.

Any ideas?

Thanks

like image 749
matzr Avatar asked Apr 25 '14 14:04

matzr


2 Answers

You could use immortal a supervisor that allows you to manage a process via HTTP either locally or remotely by using Nginx to expose the "control" Unix-socket. You could stop/start the process, send custom signals besides querying the current status and get the reply in JSON.

For example, this is a run.yml used to start the command sleep:

cmd: sleep 30
log: /var/log/sleep.log

If immortaldir is used to start services on boot time, it will create the "control" socket here:

/var/run/immortal/sleep/immortal.sock

Therefore you could configure Nginx like this:

upstream immortal {
    server unix:/var/run/immortal/sleep/immortal.sock;
}

server {
listen 80 default_server;
server_name _;
location / {
    proxy_pass http://immortal/;
    proxy_http_version 1.1;  
    proxy_redirect off;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    }
}

You may need to change permission to the socket:

chmod 766 /var/run/immortal/sleep/immortal.sock

Then via your browser, you could stop:

http://<domain>/signal/stop

Or start your process:

http://<domain>/signal/start

Further steps would be to secure the URL since everyone with access to the web server could stop/start your processes

like image 138
nbari Avatar answered Oct 04 '22 06:10

nbari


This is not certain, but a good guess would be that your php runs under a a different user than your ssh one. The one you use on ssh has some rights, the one under which php is running has others.

You can:

  1. Change your php user to be the same with the ssh one

  2. Change your file permissions to something like 777 (if security is not an issue)

  3. exec('sudo /etc/init.d/MyService.sh start', $output); - if you have sudo

  4. Change your file owner (chown)

like image 28
zozo Avatar answered Oct 04 '22 08:10

zozo