Auto run the programs When the system turns on(Debian)

14,344

Solution 1

An extremely simple solution would be to add a @reboot cron job that just runs the binary.

Do crontab -e for the user that needs to run the code (e.g. sudo crontab -e for roots crontab), and add the line

@reboot /path/to/some/executable

This will schedule the job to run each time the system has booted up.

See the crontab(5) manual for more info (man 5 crontab).

Depending on what the program does, this may be enough, or it may be too simplistic.

Solution 2

You can compile the program to say run_gpio and save it in a known path, e.g. /path/to/run_gpio. It has to be marked executable for root:

$ sudo chmod 755 /path/to/run_gpio

Then configure Debian's init system to start your program.

You can find an explanation e.g. here: http://xmodulo.com/how-to-automatically-start-program-on-boot-in-debian.html

In Debian, a directory called /etc/init.d contains a list of scripts that are executed by init process during startup and shutdown. Thus, in order to automatically run a particular program or script at startup, you can create a corresponding init.d script.

$ sudo vi /etc/init.d/run_gpio
Instead of vi, you can also use nano.

Put these lines in the new file within the init.d directory:

#! /bin/sh
# /etc/init.d/run_gpio
case "$1" in start)
/path/to/run_gpio
;; esac

Finally, make the init.d script executable, and add the init.d script to a default runlevel, so that the script can be called at boot time (and also during shutdown).

$ sudo chmod 755 /etc/init.d/run_gpio
$ sudo update-rc.d run_gpio defaults

Share:
14,344

Related videos on Youtube

Mohy Fahim
Author by

Mohy Fahim

Updated on September 18, 2022

Comments

  • Mohy Fahim
    Mohy Fahim almost 2 years

    I've got a beaglebone black that has Debian 9.1. we wrote a c++ program for its GPIOs and We want this program to always run when the system turns on. how can we do that?

    • direprobs
      direprobs almost 7 years
      You have to you use systemd unit for that.
  • Basile Starynkevitch
    Basile Starynkevitch almost 7 years
    Recent Debian uses systemd ....
  • user136036
    user136036 over 3 years
    In case anyone wonders, this edits the file /var/spool/cron/crontabs/<username> that is not accessible for a normal user though.
  • user136036
    user136036 over 3 years
    Because it's good to know where stuff is, and if someone had written my comment, I could have saved a minute to google my question :)
  • Kusalananda
    Kusalananda over 3 years
    @user136036 Well, since those files shouldn't be touched by anything other than the cron-related tools, I find it hard to comprehend why knowing where these files are stored would be helpful to anyone. Note that if you modify these files by other means than through crontab, you would have to take extra measures to make sure that the cron daemon knows about it.