How to autostart service in linux


I've got a program called redshift that I would like to autostart when I log in. If I run "redshift" in a terminal (or redshift &) or via alt+f2, this will start it. I don't think it has an init script, so will adding "redshift" to my .profile file make it load at start? I suppose a cronjob set to @reboot could also work?

I think some programs need to be executed from a certain user environment, especially those affecting graphical elements? For example, if I SSH to a remote machine and try to open up a GUI program, obviously this will not be possible so it will fail. That's what I am trying to avoid in regards to where I execute this program from.

Best Answer

redshift is not a system service; it works within your login session, as it needs to access the X11 server. So basically it should be autostarted the same way most graphical programs are:

Method 1

Add a file redshift.desktop to the XDG Autostart directory, ~/.config/autostart/:

[Desktop Entry]

This works with desktop environments that follow the XDG Autostart spec; this includes GNOME, KDE, Xfce, and many others. In some, it is editable through graphical interfaces (e.g. gnome-session-properties in GNOME).

Method 2

Add the following line...

redshift & your ~/.xprofile. This works with most display managers (gdm, kdm, lightdm, lxdm, sddm – not slim, however).

If you use the startx tool, ~/.xprofile is not used by default, so you'll have to update your ~/.xinitrc script instead – add the same line somewhere before starting the session manager.

Method 3

If you use a display manager like GDM, you might want to run the program before logging in, so that it'd apply to the login screen as well. How to do this varies between display managers, but in GDM it can be done by editing /etc/gdm/Init/Default. (Disclaimer: I haven't tried and this might be the wrong file.)

Things that will not work

  • A system init script will not work since it runs independently of graphical sessions – it won't have the right $DISPLAY nor the right $XAUTHORITY set; if you hardcode those, it might end up trying to connect to the wrong display (e.g. you hardcode DISPLAY=":0" but your session happens to start at :1); and if you make it try all displays, the script is still very likely to start before any X11 display has been started.

  • A @reboot cronjob will run as the right user (rather than needing to su/sudo), but otherwise it has all the same problems as system init scripts.

Related Question