Linux run command detach

How to Start Linux Command in Background and Detach Process in Terminal

In this guide, we shall bring to light a simple yet important concept in process handling in a Linux system, that is how to completely detach a process from its controlling terminal.

When a process is associated with a terminal, two problems might occur:

  1. your controlling terminal is filled with so much output data and error/diagnostic messages.
  2. in the event that the terminal is closed, the process together with its child processes will be terminated.

To deal with these two issues, you need to totally detach a process from a controlling terminal. Before we actually move to solve the problem, let us briefly cover how to run processes in the background.

How to Start a Linux Process or Command in Background

If a process is already in execution, such as the tar command example below, simply press Ctrl+Z to stop it then enter the command bg to continue with its execution in the background as a job.

You can view all your background jobs by typing jobs . However, its stdin, stdout, stderr are still joined to the terminal.

Run Linux Command in Background

You can as well run a process directly from the background using the ampersand, & sign.

Start Linux Process in Background

Take a look at the example below, although the tar command was started as a background job, an error message was still sent to the terminal meaning the process is still connected to the controlling terminal.

Linux Process Running in Background Message

Keep Linux Processes Running After Exiting Terminal

We will use disown command, it is used after the a process has been launched and put in the background, it’s work is to remove a shell job from the shell’s active list jobs, therefore you will not use fg , bg commands on that particular job anymore.

In addition, when you close the controlling terminal, the job will not hang or send a SIGHUP to any child jobs.

Let’s take a look at the below example of using diswon bash built-in function.

Keep Linux Process Running After Closing Terminal

You can also use nohup command, which also enables a process to continue running in the background when a user exits a shell.

Put Linux Process in Background After Closing Shell

Detach a Linux Processes From Controlling Terminal

Therefore, to completely detach a process from a controlling terminal, use the command format below, this is more effective for graphical user interface (GUI) applications such as firefox:

In Linux, /dev/null is a special device file which writes-off (gets rid of) all data written to it, in the command above, input is read from, and output is sent to /dev/null.

As a concluding remark, provided a process is connected to a controlling terminal, as a user, you will see several output lines of the process data as well as error messages on your terminal. Again, when you close the a controlling terminal, your process and child processes will be terminated.

Importantly, for any questions or remarks on the subject, reach us by using the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Running A Detached Process In Linux

Motivation

I was working on a project that involved reading from a load cell on my Raspberry Pi. I wanted to confirm that the weight measurements would stay consistent, even when the cell was loaded for a weeks at a time. To do this, I needed to find a way to continue recording measurements without keeping an ssh session open on my laptop the entire time.

Let’s Figure It Out

For the sake of this example, lets say we want to run a python script (call it test.py ) that continuously prints the current time to a file (kind of pointless but. 🤷 ).

To test it out, we run python test.py . We let the script run for a while, then interrupt it with CTRL+C . If we check the file we’ll see each timestamp output on a separate line.

Now instead, we can run the process in the background by adding an ampersand & to the end of the command. When we run it, we get an output that tells us the process id (PID).

Читайте также:  Mac os monterey обои heic

We can see a list of our current running processes using the ps command.

We can end this process using the kill -INT

If we send the default signal ( kill 4424 ), the program won’t have a chance to clean up, and everything that we wrote to the file buffer will be lost. In our case, that will be everything, since we never call flush(). If we check our output.txt, it will be empty. We need to send a signal that kills the program gracefully. Sending kill -INT 4424 will have the same effect as pressing CTRL+C when the process was running in the foreground. More info about kill can be found by running man kill or at linuxcommand.org

We still haven’t achieved our goal. This background process will be killed automatically when we logout. We need to use disown to decouple the process from our session. Taking it from the top:

Now, we logout and log back in. When we run ps , we no longer see our process. But don’t worry, it’s still there! By default, we are only shown the processes attached to our current session. We can use ps -U to see all the processes created by a given user (in my case, pi). The -f option provides more information and a nicer format.

We can leave this process running for as long as we want. Days, weeks, months — there’s no rules! (Except in this case we will run out of memory in the file buffer eventually, but you get the point). Whenever we’re done, we can gracefully kill the process using kill -INT 4432 , and make off with our super useful data.

Источник

How to detach a process from terminal in unix?

When I start a process in background in a terminal and some how if terminal gets closed then we can not interact that process any more. I am not sure but I think process also get killed. Can any one please tell me how can I detach that process from my terminal. So even if I close terminal then I can interact with same process in new terminal ?

I am new to unix so your extra information will help me.

4 Answers 4

The command you’re looking for is disown.

This is as close as you can get to a nohup. It detaches the process from the current login and allows it to continue running. Thanks David Korn!

and I just found reptyr which lets you reparent a disowned process. https://github.com/nelhage/reptyr

It’s already in the packages for ubuntu.

BUT if you haven’t started the process yet and you’re planning on doing this in the future then the way to go is screen and tmux. I prefer screen.

You might also consider the screen command. It has the «restore my session» functionality. Admittedly I have never used it, and forgot about it.

Starting the process as a daemon, or with nohup might not do everything you want, in terms of re-capturing stdout/stdin.

There’s a bunch of examples on the web. On google try, «unix screen command» and «unix screen tutorial»:

First google result for «UNIX demonizing a process»:

See the daemon(3) manpage for a short overview. The main thing of daemonizing is going into the background without quiting or holding anything up. A list of things a process can do to achieve this:

  • fork()
  • setsid()
  • close/redirect stdin/stdout/stderr to /dev/null, and/or ignore SIGHUP/SIGPIPE.
  • chdir() to /.

If started as a root process, you also want to do the things you need to be root for first, and then drop privileges. That is, change effective user to the «daemon» user or «nobody» with setuid()/setgid(). If you can’t drop all privileges and need root access sometimes, use seteuid() to temporary drop it when not needed.

If you’re forking a daemon then also setup child handlers and, if calling exec, set the close on exec flags on all file descriptors your children won’t need.

‘Interact with’ can mean a couple of things.

The reason why a program, started at the command-line, exits when the terminal ends, is because the shell, when it exits, sends that process a HUP signal (see documentation for kill(1) for some introduction; HUP, by the way, is short for ‘hang up’, and originally indicated that the user had hung up the modem/telephone). The default response to a HUP signal is that a process is terminated – that is, the invoked program exits.

The details are slightly more fiddly, but this is the general intuition.

The nohup command tells the shell to start the program, and to do so in a way that this HUP signal is ignored. That is, the program keeps going after the invoking terminal exits.

You can still interact with this program by sending it signals (see kill(1) again), but this is a very limited sort of interaction, and depends on your program being written to do sensible things when it receives those signals (signals USR1 and USR2 are useful things to trap, if you’re into that sort of thing). Alternatively, you can interact via named pipes, or semaphores, or other bits of inter-process communication (IPC). That gets fiddly pretty quickly.

Читайте также:  Windows server 2012 интерфейс пользователя

I suspect what you’re after, though, is being able to reattach a terminal to the process. That’s a rather more complicated process, and applications like screen do suitably complicated things behind the scenes to make that happen.

The nohup thing is a sort of quick-and-dirty daemonisation. The daemon(3) function does the daemonisation ‘properly’, doing various bits of tidy-up as described in YePhIcK’s answer, to comprehensively break the link with the process/terminal that invoked it. You can interact with that daemonised process with the same IPC tools as above, but not straightforwardly with a terminal.

Источник

How to execute a command in screen and detach?

How can I get screen to execute a command and then detach (That is, automatically in a single script without further input beyond initially starting the script)? e.g. I run myscript.sh and it automatically starts a screen session, executes a command, then detaches.

7 Answers 7

This is an easy one:

-d -m
Start screen in detached mode. This creates a new session but doesn’t attach to it. This is useful for system startup scripts.

/.screenrc . It should also be possible to enable it for one session only b putting zombie xy in another file and using -c file but for some reason that’s not working when I try it. Or just use sh -c ‘yourcommand;while :;do sleep 9999; done’

To run a single command in screen and detach, you may try:

To run multiple commands, try:

Please note that when a program terminates, screen (per default) kills the window that contained it.

If you don’t want your session to get killed after script is finished, add exec sh at the end, e.g.:

To list all your sessions, try:

In order to start new session in background with name ‘sleepy’

In order to kill ‘sleepy’ session

it happen to me when I pressed control c (sig int) to exit my program. it exits all the way from all bash. so I found this to catch SIGINT. and prevent exit from last bash. (need to type exit to exit)

I find it useful to use cron to run nodejs programs on startup. and to run the screen at boot time. in cron there are special events syntax @reboot event

Here are the steps you can follow to run a process in screen, detach from the terminal, and then reattach.

From the command prompt, just run screen . This will give you a new subshell.

Run your desired program

Detatch from the screen session using the key sequence Ctrl-a Ctrl-d (note that all screen key bindings start with Ctrl-a ). This will drop you back to your original shell and display a message «[detached]», indicating that the screen session is still running.

You can then list the available screen sessions by running screen -list

You can reattach to this screen session by running screen -r . Once reattached, you will be able to take off where you left off and see any output that was printed to the screen during the time that you were detached. If you have multiple screen sessions, then you can specify the tty name (as displayed by screen -list ) as an argument to screen -r to attach to a particular session.

Источник

How do I detach a process from Terminal, entirely?

I use Tilda (drop-down terminal) on Ubuntu as my «command central» — pretty much the way others might use GNOME Do, Quicksilver or Launchy.

However, I’m struggling with how to completely detach a process (e.g. Firefox) from the terminal it’s been launched from — i.e. prevent that such a (non-)child process

  • is terminated when closing the originating terminal
  • «pollutes» the originating terminal via STDOUT/STDERR

For example, in order to start Vim in a «proper» terminal window, I have tried a simple script like the following:

However, that still causes pollution (also, passing a file name doesn’t seem to work).

21 Answers 21

First of all; once you’ve started a process, you can background it by first stopping it (hit Ctrl — Z ) and then typing bg to let it resume in the background. It’s now a «job», and its stdout / stderr / stdin are still connected to your terminal.

You can start a process as backgrounded immediately by appending a «&» to the end of it:

To run it in the background silenced, use this:

Some additional info:

nohup is a program you can use to run your application with such that its stdout/stderr can be sent to a file instead and such that closing the parent script won’t SIGHUP the child. However, you need to have had the foresight to have used it before you started the application. Because of the way nohup works, you can’t just apply it to a running process.

disown is a bash builtin that removes a shell job from the shell’s job list. What this basically means is that you can’t use fg , bg on it anymore, but more importantly, when you close your shell it won’t hang or send a SIGHUP to that child anymore. Unlike nohup , disown is used after the process has been launched and backgrounded.

Читайте также:  Как отключить или удалить защитник windows 10

What you can’t do, is change the stdout/stderr/stdin of a process after having launched it. At least not from the shell. If you launch your process and tell it that its stdout is your terminal (which is what you do by default), then that process is configured to output to your terminal. Your shell has no business with the processes’ FD setup, that’s purely something the process itself manages. The process itself can decide whether to close its stdout/stderr/stdin or not, but you can’t use your shell to force it to do so.

To manage a background process’ output, you have plenty of options from scripts, «nohup» probably being the first to come to mind. But for interactive processes you start but forgot to silence ( firefox /dev/null & ) you can’t do much, really.

I recommend you get GNU screen . With screen you can just close your running shell when the process’ output becomes a bother and open a new one ( ^Ac ).

Oh, and by the way, don’t use » $@ » where you’re using it.

$@ means, $1 , $2 , $3 . which would turn your command into:

That’s probably not what you want because -e only takes one argument. Use $1 to show that your script can only handle one argument.

It’s really difficult to get multiple arguments working properly in the scenario that you gave (with the gnome-terminal -e ) because -e takes only one argument, which is a shell command string. You’d have to encode your arguments into one. The best and most robust, but rather cludgy, way is like so:

nohup detaches the process completely (daemonizes it)

If you are using bash , try disown [jobspec] ; see bash(1).

Another approach you can try is at now . If you’re not superuser, your permission to use at may be restricted.

Reading these answers, I was under the initial impression that issuing nohup & would be sufficient. Running zsh in gnome-terminal, I found that nohup & did not prevent my shell from killing child processes on exit. Although nohup is useful, especially with non-interactive shells, it only guarantees this behavior if the child process does not reset its handler for the SIGHUP signal.

In my case, nohup should have prevented hangup signals from reaching the application, but the child application (VMWare Player in this case) was resetting its SIGHUP handler. As a result when the terminal emulator exits, it could still kill your subprocesses. This can only be resolved, to my knowledge, by ensuring that the process is removed from the shell’s jobs table. If nohup is overridden with a shell builtin, as is sometimes the case, this may be sufficient, however, in the event that it is not.

disown is a shell builtin in bash , zsh , and ksh93 ,

if you prefer one-liners. This has the generally desirable effect of removing the subprocess from the jobs table. This allows you to exit the terminal emulator without accidentally signaling the child process at all. No matter what the SIGHUP handler looks like, this should not kill your child process.

After the disown, the process is still a child of your terminal emulator (play with pstree if you want to watch this in action), but after the terminal emulator exits, you should see it attached to the init process. In other words, everything is as it should be, and as you presumably want it to be.

What to do if your shell does not support disown ? I’d strongly advocate switching to one that does, but in the absence of that option, you have a few choices.

  1. screen and tmux can solve this problem, but they are much heavier weight solutions, and I dislike having to run them for such a simple task. They are much more suitable for situations in which you want to maintain a tty, typically on a remote machine.
  2. For many users, it may be desirable to see if your shell supports a capability like zsh’s setopt nohup . This can be used to specify that SIGHUP should not be sent to the jobs in the jobs table when the shell exits. You can either apply this just before exiting the shell, or add it to shell configuration like

/.zshrc if you always want it on.

  • Find a way to edit the jobs table. I couldn’t find a way to do this in tcsh or csh , which is somewhat disturbing.
  • Write a small C program to fork off and exec() . This is a very poor solution, but the source should only consist of a couple dozen lines. You can then pass commands as commandline arguments to the C program, and thus avoid a process specific entry in the jobs table.
  • Источник

    Оцените статью