Linux return to stopped process

Как я могу возобновить остановленную работу в 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:

  1. Using the Ctrl + Z shortcut (for a process running in the foreground)
  2. 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:

Читайте также:  Linux централизованная установка приложений

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.

Example of suspending a process in Linux

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:

list background processes

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:

terminate the process using kill command in terminal

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:

resume the terminated process in Linux

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.

Читайте также:  Linux для ноутбуков на русском

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 succeeded to restore it.

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 run a command after an already running, existing one finishes?

If I start a script that is going to take a long time, I inevitably realize it after I’ve started the script, and wish I had a way of doing some kind of alert once it finishes. So, for example, if I run:

5 Answers 5

You can separate multiple commands by ; , so they are executed sequentially, for example:

really_long_script.sh ; echo Finished 

If you wish to execute next program only if the script finished with return-code 0 (which usually means it has executed correctly), then:

really_long_script.sh && echo OK 

If you want the opposite (i.e. continue only if current command has failed), than:

really_long_script.sh || echo FAILED 

You could run your script in a background (but beware, scripts output ( stdout and stderr ) would continue to go to your terminal unless you redirect it somewhere), and then wait for it:

really_long_script.sh & dosomethingelse wait; echo Finished 

If you have already run script, you could suspend it with Ctrl-Z , and then execute something like:

Where fg brings the suspended process to foreground ( bg would make it run in background, pretty much like started with & )

Since fg returns the value of the job it resumes, you can use fg && echo Finished if you want to ensure the command succeeds before executing the other command.

Ctrl+Z stops a process (for me at least?). fg seems to start the same command again. In the case of youtube-dl or some other extremely well written programs, that might work, but not for most.

@FabianRöling Ctrl-Z pauses a process (by sending SIGHUP), and bg or fg later resumes it (not starts it again). You can try launching some GUI application from a terminal, then press Ctrl-Z in terminal (the app will freeze), then do fg (the app will become responsive again). I never encountered any issues despite extensively using Ctrl-Z for many years for a variety of programs. It messes up some fancy screen output (e.g., progressbar), but that is to be expected since you temporary take control of the terminal.

@FabianRöling Yes, it says «stopped». But you can call jobs in the same console to see that the process is still there (albeit, indeed, in a paused/stopped state). You can also call ps a and see that the process still exists. It’s stopped, but not terminated, and can be resumed (by fg or bg ). If you try to close the console by typing exit (instead of closing the terminal window) it will complain about the stopped process.

Читайте также:  Fdisk linux удалить раздел

If the process does not run on current tty, then try this:

watch -g ps -opid -p ; mycommand 
really_long_script.sh ^Z (Ctrl-Z) [1]+ Stopped really_long_script.sh $ fg ; mycommand # OR: To run "mycommand" ONLY IF "really_long_script.sh" has finished successfully: $ fg && mycommand 

You can also use bash’s job control. If you started

then press ctrl+z to suspend it:

^Z [1]+ Stopped really_long_script.sh $ bg 

to restart the job in the background (just as if started it with really_long_script.sh & ). Then you can wait for this background job with

$ wait N && echo "Successfully completed" 

where N is the job ID (probably 1 if you didn’t run any other background jobs) which is also displayed as [1] above.

Turns out this isn’t that hard: You can simply type the next command into the window while the existing one runs, press enter, and when the first one finishes, the second command will automatically run.

I’m guessing there are more elegant ways, but this does seem to work.

Editing to add that if you want to run an alert after the command finishes, you can create these aliases in .bashrc, then run alert while it is running:

 alias alert_helper='history|tail -n1|sed -e "s/^\s*2\+\s*//" -e "s/;\s*alert$//"' alias alert='notify-send -i gnome-terminal "Finished Terminal Job" "[$?] $(alert_helper)"' 

A while ago I have written a script to wait for the end of another process. NOISE_CMD could be something like notify-send . , given that DISPLAY is set correctly.

#!/bin/bash NOISE_CMD="/usr/bin/mplayer -really-quiet $HOME/sfx/alarm-clock.mp3" function usage() < echo "Usage: $(basename "$0") [ PROCESS_NAME [ PGREP_ARGS. ] ]" echo "Helpful arguments to pgrep are: -f -n -o -x" >if [ "$#" -gt 0 ] ; then PATTERN="$1" shift PIDS="$(pgrep "$PATTERN" "$@")" if [ -z "$PIDS" ] ; then echo "No process matching pattern \"$PATTERN\" found." exit fi echo "Waiting for:" pgrep -l "$PATTERN" "$@" for PID in $PIDS ; do while [ -d "/proc/$PID" ] ; do sleep 1 done done fi exec $NOISE_CMD 

Without any argment, just make some noise immediately. This behavoir allows something like this for convenience (say you call script below alarm.sh ):

apt-get upgrade ; ~/bin/alarm.sh 

Of course you can do many funny things with such a script, like letting an instance of alarm.sh wait for an instance of alarm.sh , that is waiting for some other command. Or executing a command just right after some task of a other logged in user has finished. >:D

A former version of the script above might be interesting, if you want to avoid a dependency on pgrep and accept to lookup process IDs yourself:

#!/bin/bash if [ "$#" -lt 2 -o ! -d "/proc/$1" ] ; then echo "Usage: $(basename "$0") PID COMMAND [ ARGUMENTS. ]" exit fi while [ -d "/proc/$1" ] ; do sleep 1 done shift exec "$@" 

Slightly off-topic, but useful in similar situations: One might be interested in reptyr , a tool that «steals» a process from some (parent) shell and runs it in from current shell. I have tried similar implementations and reptyr is the prettiest and most reliable for my purposes.

Источник

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