I have compiled a C++ program. I works fine, but when I close the terminal the program stops. How can I run this program as service and It restarts when the computer will be rebooted or the the process stopped?
There are several ways to get there from here.
If your program needs to run constantly you can create a systemd service, as described here:
If your program needs to run periodically you can create a cronjob, as described here:
If your program needs to run in the background from a user’s session you can look at Linux job control, as described here:
Another option is the screen command, as described here:
My program works fine with systemd. With
journalctl -u program I can see the log. It is great, but how can I see the original program in the shell without to stop the systemd?
This doesn’t make sense. If the program is supposed to run as a service, e.g. after a reboot, there won’t be any shell, and no one would be logged in, and so no one can see it. In that case, you have to use the logs.
You can run it in screen. I have done this once. And the screen process was started via systemd. Will have to dig out how I did it and post it here shortly.
So first I create a script to start the program:
#!/bin/bash screen -dmS my-program-name /usr/local/bin/my-program
my-program-name is just some text to identify the screen session easily. The second part
my-program being the program you want to run, eg: your C++ program. Let’s say we name the above script
Now, you run start-my-program.sh with systemd. If you want to connect to your program via screen, then you do something like this:
screen -r my-program-name
with that being the name given in the script that was created. You can then view the program, and disconnect from screen using CTRL+A and then pressing D. The process will then still be running after you disconnected from it.
It might even be possible to bypass the script altogether and just run the screen command in the systemd script itself. Whatever works best for you.