setsid how to keep commands running after exiting shell prompt

If you need to run any program or command, and then leave the shell session or ssh session, but be sure to leave the command running behind you, then you can use setsid.

I know you are going to mention screen and nohup, and yes they are maybe better options, but setsid is another option.

setsid creates a new session id for the command you run using it, so it does not deppend on your shell session, therefore if that shell session is closed the other command will stay running.

setsid – Running a command in a new session

One thing must be clarified, using screen and nohup, you can return and check the output of the running commands, with screen because you can attach a screen session, and with nohup, because you can check the output file.

Using setsid that is not possible, so only use it, when the output is not important for you.

For example, you can run a command that writes its output to a file, like this:

setsid free > /tmp/free-memory.txt

This way the output will be in the file /tmp/free-memory.txt and you can always check that file using tail.

setsid – How the new sessions work

I will use pstree, to show you the difference of run a command with and without setsid

The command to be run will top, with top running, I run pstree and here is the output:

     |-kdeinit4—klauncher

     |-klogd

     |-knotify4

     |-konsole-+-bash—vim

     |         |-bash—top

     |         |-bash—pstree

     |         `-{konsole}

Now, lets run setsid top instead of just top, and the output of pstree

     |-knotify4

     |-konsole-+-bash—vim

     |         |-bash

     |         |-bash—pstree

     |         `-{konsole}

     |-sshd

     |-syslogd

     |-top

As you can see, now top is in the root of the tree, while before it was a child of konsole.

Neelesh Gurjar has written 122 articles

One thought on “setsid how to keep commands running after exiting shell prompt

Leave a Reply