Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash init - start service under specific user

I am trying to create an init script in bash (Ubuntu) that starts a service under a specific user.

Is there a better way to do that other than this?

su - <user>  -c "bash -c  'cd $DIR ;<service name>'"
like image 596
David Ryder Avatar asked Sep 19 '11 02:09

David Ryder


People also ask

What is init service in Linux?

init is the first process that starts in a Linux system after the machine boots and the kernel loads into memory. Among other things, it decides how a user process or a system service should load, in what order, and whether it should start automatically.


2 Answers

Ubuntu uses start-stop-daemon which already supports this feature.

Use the skeleton file from /etc/init.d:

sudo cp /etc/init.d/skeleton /etc/init.d/mynewservice

Edit mynewservice appropriately.

Add the following parameter to the lines that call start-stop-daemon:

--chuid username:group

Example:

Change

start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \

to

start-stop-daemon --start --quiet --chuid someuser:somegroup --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \

Finally, register your service and start it:

update-rc.d mynewservice defaults 99 && service mynewservice start

More info about other options for start-stop-daemon here

like image 115
Carl Avatar answered Oct 02 '22 14:10

Carl


Alternatively, you can use the daemon function defined in your /etc/init.d/functions file:

daemon --user=<user> $DIR/program

If you look into its syntax you can do other things like defining PID file location, setting nice level, and whatnot. It's otherwise really useful for starting up services as daemons. Services started up with daemon can easily be terminated by another functions function, killproc.

like image 44
Manny D Avatar answered Oct 02 '22 12:10

Manny D