- Как я могу возобновить остановленную работу в Linux?
- How to Suspend and Resume Processes in Linux [Quick Tip]
- Suspending the process in Linux
- 1. Suspend a foreground process
- 2. Suspend a process by sending STOP signal
- Resuming the process again
- Know more about termination signals
- How can I resume a stopped job in Linux?
- 5 Answers 5
- How to suspend and resume processes
- 2 Answers 2
- How to start a stopped process in Linux
- 2 Answers 2
Как я могу возобновить остановленную работу в Linux?
Команда fg — это то, что вы хотите использовать. Вы также можете указать номер задания, если остановлено несколько заданий.
- jobs — список текущих работ
- fg — возобновить работу, которая следующая в очереди
- fg% [число] — возобновить работу [номер]
- bg — выдвинуть следующее задание в очереди в фоновый режим
- bg% [число] — отодвинуть задание [число] на задний план
- kill% [число] — убить задание с номером [число]
- kill — [сигнал]% [номер] — отправить сигнал [сигнал] на номер задания [номер]
- disown% [число] — отменить процесс (терминал больше не будет владельцем), поэтому команда будет работать даже после закрытия терминала.
Это почти все из них. Обратите внимание на% infront номера задания в командах — это то, что говорит kill, вы говорите о заданиях, а не процессах.
Вы также можете ввести % ; то есть вы нажимаете Ctrl-Z в emacs, затем вы можете набрать %emacs в консоли и вернуть его на передний план.
Просто чтобы добавить к другим ответам, Bash позволяет пропустить fg если вы указали номер работы.
Например, они эквивалентны и возобновляют последнюю работу:
Если вы не запускали его с текущего терминала, используйте ps aux | grep чтобы найти номер процесса (pid), затем возобновите его с:
(Несмотря на название, kill — это просто инструмент для отправки сигнала процессу, позволяющий процессам взаимодействовать друг с другом. «Сигнал уничтожения» — это только один из многих стандартных сигналов.)
Дополнительный совет: оберните первый символ имени процесса с помощью [] чтобы в результатах не отображалась сама команда grep . например, чтобы найти процесс emacs , используйте ps aux | grep [e]macs
How to Suspend and Resume Processes in Linux [Quick Tip]
Learn how to suspend a running process in the Linux command line. Also learn how to resume a stopped process.
Have you ever encountered a situation where you have to suspend an ongoing task as you have more important tasks to execute and want to resume the previous task later?
Actually, it is possible and can be done pretty easily using two termination signals: STOP and CONT .
And in this guide, I will walk you through step-by-step to suspend and resume the process again in Linux.
Suspending the process in Linux
You have two options to suspend the process:
- Using the Ctrl + Z shortcut (for a process running in the foreground)
- Using the kill command with the STOP signal
A suspended process is denoted as stopped in the terminal. This may confuse you but the ‘stopped process’ can be resumed. After all, there is a difference between stop (SIGSTOP) and termination (SIGTERM).
1. Suspend a foreground process
Let me give you an example you can see. I run Firefox from the command line with this command:
The browser runs and you can see some strange output on the terminal. That’s okay.
No, I suspend the Firefox process which is running in the foreground with the Ctrl+z terminal shortcut:
And here is what happens. The Firefox process is suspended and you can see it in the terminal. After a few seconds of delay, a dialogue box popups to notify that the Firefox browser is not responding anymore.
2. Suspend a process by sending STOP signal
When the process is running in the background, you can not use the Ctrl + Z shortcut. In that case, you’d have to use the kill command.
Let’s see this with an example. I run the sleep command for a really long time. But I am running the command in the background by adding & to it.
You can verify the background processes using the jobs command:
I can see the process ID in the example. There are various ways to find process ID. You can use the ps command and grep on the process name.
Once you have the process ID, you can suspend the process using the kill command in the following manner:
In my case, the PID is 26589, then, I’d have to use the following command:
And as you can see, the process is stopped successfully.
Resuming the process again
To resume the process, you’d have to use the CONT flag with the kill command as shown:
In my case, the PID was 26589 then, the command would be:
And as you can see, after resuming the process, I used the jobs command, which showed the process was running as it should.
Know more about termination signals
Apart from STOP and TERM signals which I explained above, the kill command offers various other termination signals to kill the process with different effects.
And we made a detailed guide for how you can use the most popular ones:
I hope you will find this quick tip helpful.
How can I resume a stopped job in Linux?
This is actually a fairly normal work flow for Vim, if you want to keep you commands in your bash history, then you hit Ctrl-z type your commands and then resume. Obviously you can run commands without leaving Vim via the :! ed command
5 Answers 5
The command fg is what you want to use. You can also give it a job number if there are more than one stopped jobs.
The general job control commands in Linux are:
- jobs — list the current jobs
- fg — resume the job that’s next in the queue
- fg %[number] — resume job [number]
- bg — Push the next job in the queue into the background
- bg %[number] — Push the job [number] into the background
- kill %[number] — Kill the job numbered [number]
- kill -[signal] %[number] — Send the signal [signal] to job number [number]
- disown %[number] — disown the process(no more terminal will be owner), so command will be alive even after closing the terminal.
That’s pretty much all of them. Note the % infront of the job number in the commands — this is what tells kill you’re talking about jobs and not processes.
Why use «%» character. Is it required to be prepended before the job number or Is it a unix convention to specify the int type ?
You can also type % ; i.e., you hit Ctrl-Z in emacs, then you can type %emacs in the console and bring it back to the foreground.
Just to add to the other answers, bash lets you skip the fg if you specify a job number.
For example, these are equivalent and resume the latest job:
% is awesome, thanks! As a touch-typist, I find fg very irritating (same finger). But then, so is cd .
in my case when i tried to use fg i see the stopped process appears and disappears quickly and just
If you didn’t launch it from current terminal, use ps aux | grep to find the process number (pid), then resume it with:
(Despite the name, kill is simply a tool to send a signal to the process, allowing processes to communicate with each other. A «kill signal» is only one of many standard signals.)
Bonus tip: wrap the first character of the process name with [] to prevent the grep command itself appearing in the results. e.g. to find emacs process, use ps aux | grep [e]macs
How to suspend and resume processes
In the bash terminal I can hit Control + Z to suspend any running process. then I can type fg to resume the process. Is it possible to suspend a process if I only have it’s PID? And if so, what command should I use? I’m looking for something like:
suspend-process $PID_OF_PROCESS
resume-process $PID_OF_PROCESS
2 Answers 2
You can use kill to stop the process.
For a ‘polite’ stop to the process (prefer this for normal use), send SIGTSTP :
For a ‘hard’ stop, send SIGSTOP :
Note that if the process you are trying to stop by PID is in your shell’s job table, it may remain visible there, but terminated, until the process is fg ‘d again.
To resume execution of the process, sent SIGCONT :
Unless there are other reasons for it, I would prefer SIGTSTP over SIGSTOP, as some applications do handle SIGTSTP specially. For example, if scp is showing a progress bar, SIGTSTP will cause it to clean up the terminal mode before suspending, but if you send SIGSTOP, it will not have a chance to do so.
@ephemient I tried SIGTSTP, I saw what you were saying about it cleaning up the terminal. Thanks for the explanation of SIGTSTP, alawys good to learn new things 🙂
Also useful to note that you can reference the [pid] value by using the % symbol and then the job number (one that you can find by running jobs ). So you’d go: kill -TSTP %1
Why do you mean by it may remain visible there, but terminated ? It’s not terminated but stopped/paused. I tried kill -STOP and it behaves exactly like kill -TSTP for shell jobs.
You should use the kill command for that.
To be more verbose — you have to specify the right signal, i.e.
for suspending the process and
for resuming it. Documented at 24.2.5 Job Control Signals.
I wonder what accident of history led to this answer getting fewer votes? The answers are nearly the same and this one came first.
@Wildcard, when I created the answer I was a bit in a hurry, thus, it basically just contained the first part up to kill -TSTP (i.e. how to suspend). 1/2 year later, i.e. 2011, I revisited my answer and noticed its incompleteness. Thus, I edited it and added also the kill -CONT part. This should explain the difference in votes in comparison with Steve’s answer.
How to start a stopped process in Linux
I have a stopped process in Linux at a given terminal. Now I am at another terminal. How do I start that process. What kill signal would I send. I own that process.
2 Answers 2
You can issue a kill -CONT pid, which will do what you want as long as the other terminal session is still around. If the other session is dead it might not have anywhere to put the output.
In addition to @Dave’s answer, there is an advanced method to redirect input and output file descriptors of a running program using GDB.
A FreeBSD example for an arbitrary shell script with PID 4711:
> gdb /bin/sh 4711 . Attaching to program: /bin/sh, process 4711 . (gdb) p close(1) $1 = 0 (gdb) p creat("/tmp/testout.txt",0644) $2 = 1 (gdb) p close(2) $3 = 0 (gdb) p dup2(1,2) $4 = 2
EDIT — explanation: this closes filehandle 1, then opens a file, which reuses 1. Then it closes filehandle 2 and duplicates filehandle 1 to 2.
Now this process’ stdout and stderr go to indicated file and are readable from there. If stdin is required, you need to p close(0) and then attach some input file or PIPE or smth.
For the time being, I could not find a method to remotely disown this process from the controlling terminal, which means that when the terminal exits, this process receives SIGHUP signal.
Note: If you do have/gain access to the other terminal, you can disown -a so that this process will continue to run after the terminal closes.