BASH - How to execute Unix/Linux script/commands after ending the terminal session (sending the process SIGHUP signal)

BASH - How to execute Unix/Linux script/commands after ending the terminal session (sending the process SIGHUP signal)

Hi everyone, I wanted to write this brief post about executing a script/command in a Unix/Linux environment and still be running even after closing the current terminal session.

As we know, every time we open a terminal, it's associated a PID (Process ID) to it. When we run a command inside such terminal, it forks (creates a child process). When the script/command finishes, the terminal sends a SIGHUP signal to the child process, closes it, and returns to the parent process. However, when we close the current session, the terminal sends a SIGHUP signal to every child process that has been generated by the parent process. Therefore all the scripts/commands that are currently running will be terminated.

That been said, let's suppose the following scenario.

We are running some find command to search for all the files with just one letter in their filename, it's taking too long, and we need to unplug our ethernet cable.

Our find command is the following:

$find / -iname [A-Za-z] > $HOME/empty_output.out 2>/dev/null

We send a SIGSTOP signal to the Find process with the CTRL+Z keyboard combination.

No alt text provided for this image

After stopping it, we see our current jobs with the Jobs and the ps aux command. In the ps aux command, we can see the letter T, for the PROCESS STATE CODES, which means a process that has been stopped by the job control signal.

$jobs

$ps aux | grep --colour "find"

No alt text provided for this image

After we get PID for the find child process (1), we can now send it to the background with the command bg %PID

$bg %1

No alt text provided for this image

Finally, we disown the job from the current shell's job list with the disown command.

$disown -a

$exit

No alt text provided for this image

 See that the jobs running are disowned from the current shell's job, but they are still connected to the terminal. The program will fail as soon as it tries to read from standard input or write to standard output. After the child process is disowned from the parent process, we can close the connection, and our Find process will run until it finishes without ending abruptly due to the SIGHUP signal.

The following picture shows all the commands used in this article.

No alt text provided for this image

Thanks for reading!






To view or add a comment, sign in

More articles by Óscar Azeem B.

Others also viewed

Explore content categories