[Linux] How to Excute Binary in Background

linux-execute-a-binary-in-background

1. Problem

You may meet the situation where you want to execute a binary in Linux, but you don’t want to keep the terminal open. You want to close the terminal and let the binary run in the background.

2. Solution

In Linux, you can use the nohup command to run a binary in the background. The nohup command is used to run a command or script that keeps running after you log out of a shell.

Let’s say you have a binary called crontool and you want to run it in the background. You can use the following command:

2.1 Run a Binary in the Background

nohup sudo /home/ubuntu/bin/crontool -f "@every 12h" 

2.2 Run a Binary in the Background and Redirect Output to a log File

This is quite useful if you want to keep track of the output of the binary. You can redirect the output to a log file so that you can check the log file later.

nohup sudo /home/ubuntu/bin/crontool -f "@every 12h" > /home/ubuntu/logs/crontool.log 2>&1 &

2.3 Run a Binary in the Background with Environment Variables

If you need to pass environment variable to the binary, you can use the -E option to pass your current environment variables to the command you are running.

export ENV_VAR1=value1
nohup sudo -E /home/ubuntu/bin/crontool -f "@every 12h" > /home/ubuntu/logs/crontool.log 2>&1 &

2.4 Run a Binary in the Background with the Shell Script

You can also create a shell script to run the binary in the background. This is even more convenient if you want to run the binary with a specific set of environment variables or your binary has a long command line.

#!/bin/bash

export ENV_VAR1=value1
nohup sudo -E /home/ubuntu/bin/crontool -f "@every 12h" > /home/ubuntu/logs/crontool.log 2>&1 &

Save the above script to a file called run_crontool.sh and make it executable:

chmod +x run_crontool.sh

Then you can run the script to start the binary in the background:

./run_crontool.sh

3. Other Relevant Commands

3.1 Find your Running Background Processes

If your binary needs to update or restart, you may want to find the process ID of the running background process. You can use the ps command to find the process ID of the running background process.

ps -ef | grep crontool

3.2 Kill a Running Background Process

If you want to stop the running background process, you can use the kill command to kill the process by its process ID.

kill -9 <process_id>

4. Summary

In this post, we have learned how to run a binary in the background in Linux using the nohup command. We have also learned how to redirect the output of the binary to a log file and how to pass environment.


If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !