Linux resume stopped jobs

There are stopped jobs (on bash exit)

I get the message There are stopped jobs. when I try to exit a bash shell sometimes. Here is a reproducible scenario in python 2.x:

  • ctrl + c is handled by the interpreter as an exception.
  • ctrl + z ‘stops’ the process.
  • ctrl + d exits python for reals.

Here is some real-world terminal output:

Bash did not exit, I must exit again to exit the bash shell.

  • Q: What is a ‘stopped job’, or what does this mean?
  • Q: Can a stopped process be resumed?
  • Q: Does the first exit kill the stopped jobs?
  • Q: Is there a way to exit the shell the first time? (without entering exit twice)

2 Answers 2

A stopped job is one that has been temporarily put into the background and is no longer running, but is still using resources (i.e. system memory). Because that job is not attached to the current terminal, it cannot produce output and is not receiving input from the user.

You can see jobs you have running using the jobs builtin command in bash, probably other shells as well. Example:

You can resume a stopped job by using the fg (foreground) bash built-in command. If you have multiple commands that have been stopped you must specify which one to resume by passing jobspec number on the command line with fg . If only one program is stopped, you may use fg alone:

At this point you are back in the python interpreter and may exit by using control-D.

Conversely, you may kill the command with either it’s jobspec or PID. For instance:

To use the jobspec, precede the number with the percent (%) key:

If you issue an exit command with stopped jobs, the warning you saw will be given. The jobs will be left running for safety. That’s to make sure you are aware you are attempting to kill jobs you might have forgotten you stopped. The second time you use the exit command the jobs are terminated and the shell exits. This may cause problems for some programs that aren’t intended to be killed in this fashion.

In bash it seems you can use the logout command which will kill stopped processes and exit. This may cause unwanted results.

Also note that some programs may not exit when terminated in this way, and your system could end up with a lot of orphaned processes using up resources if you make a habit of doing that.

Note that you can create background process that will stop if they require user input:

You can resume and kill these jobs in the same way you did jobs that you stopped with the Ctrl-z interrupt.

Источник

How To Suspend A Process And Resume It Later In Linux

Picture this scenario. You run a program. But, you don’t know how long it will take to finish. The process keeps running several minutes. You can’t wait that much longer, because some other important programs are waiting in the queue. Have you ever been in a situation like this? No worries! I just found a simple trick to suspend a process and resume it later in Linux.

What I am going to do is just pause the currently running process, do some other important tasks, and then resume the stopped process after all other processes are completed. This can be very useful when you have less RAM or Processor to do multi-task. You can pause the running processes at any time, and resume them later, without having to start them all over again. Now let us go ahead and learn to suspend or pause a running process and resume it later in Linux and Unix-like operating systems.

Suspend a process and resume it later in Linux

This is absolutely an easy! All you have to do is find the PID (Process ID) and using ps or ps aux command, and then pause it, finally resume it using kill command.

Читайте также:  Windows server 2016 активация сервера лицензирования

Let us see an example. I am going to download Ubuntu 18.04 netboot image using wget command:

Here, & symbol will move the running task (i.e. wget ) to the background without closing it.

Now, I want to pause this task and run other important tasks. To do so, first find the running processes using command:

Sample output:

As you see, the PID of wget command is 16143.

Let us stop this process now. To do so, run the following command from your Terminal:

Verify whether the process has been stopped or not using command:

Sample output:

See? The wget process has been stopped.

Go ahead and do other important tasks. Once all tasks are completed, resume the stopped process using command:

To verify it if the process is running, run ps command.

Suspend a process and resume it later in Linux

See? The process which we stopped earlier has been resumed!

Like I said already, this will be helpful if you can’t do multi-task in system that has low RAM or CPU speed.

First, find the pid of the running process using ps command. Then, pause it using kill -STOP

, and then hibernate your system. Resume your system and resume the stopped process using command kill -CONT

Does this work after restarting my system?

You might wonder, will this also work after a full system shutdown or reboot? NO. Because, the PIDs of the processes will automatically change after rebooting your system. They do not persist across reboot. In such cases, you can suspend or hibernate your entire system, and resume them when you are ready.

And, that’s all. You know now how to pause and resume a process in Linux and Unix-like operating systems. Hope this helps.

Источник

How can I kill all stopped jobs?

When I try to exit from my Linux server I get the message:

There are stopped jobs.

: Is there a single command to kill these?

8 Answers 8

To quickly kill all the stopped jobs under the bash, enter:

jobs -ps lists the process IDs ( -p ) of the stopped ( -s ) jobs.
kill -9 `jobs -ps` sends SIGKILL signals to all of them.

Try typing this:

The accepted answer would kill all jobs (which is sufficient in this case) and not merely the stopped ones. Should you want to kill only the Stopped ones, run:

The easiest way is actually to simply immediately retry the exit; bash will take that to mean «kill all stopped jobs and exit».

Normally if you got that message, you need to logout twice. E.g. first Ctrl+D gives you the warning message to inform you about stopped jobs, pressing for the second time will log you out killing the jobs. This the same applies to logout and exit commands.

To kill them manually, try: kill $(jobs -p) .

If you don’t want to kill jobs from your current shell, you can remove them from the table of active jobs without killing by using disown command. E.g.

Stopped jobs also can be determined by the state of the process ( T character) which means the process was stopped by signal such as SIGSTOP , SIGTSTP or other (like SIGTTIN , or SIGTTOU ).

In case when jobs a shell builtin command is not available, stopped processes can be listed by the following command:

Источник

Управление заданиями

Наверное всякий nix-оид знает что запуская команду с амперсандом на конце — она уходит в фон, продолжая работу.
Таким образом запущенная команда превращается в job (задание).
Более продвинутые знают что можно вывести список запущенных заданий командой jobs, и переключиться между ними командами fg (вывести фоновую задачу в оболочку)/ bg (отправить остановленное задание в фон). Остальными командами пользуются куда реже, а большинство начинающих линуксоидов про них читали мельком, но забыли, или вообще никогда не знали. А между прочим кроме: jobs, fg и bg есть disown, wait и даже kill.
Не считая тех, что можно использовать внутри задания или для управления написанными выше командами: enable, builtin.
Итак если вам интересно как делается:
1. Приостановка job-в. Остановка (kill).
2. Запуск ранее приостановленного job-а.
3. Advanced нумерация заданий.
4. Ожидание завершения фоновых задач.
5. Команда disown.

Запустим три задания:
$ nice gzip /dev/null &
[1] 15727
$ bzip2 /dev/null &
[2] 15728
$ xz /dev/null &
[3] 15730

Три задания, с номерами 1, 2, 3. и их PID-ами.

Читайте также:  Где найти значки для папок windows

Остановка заданий

Приостановка

Приостанвим задание, например первое:
это сделает команда kill, передавая сигнал SIGSTOP.

В данном случае использовалась внутренняя команда bash-а: kill, а не внешняя программа /bin/kill.
Да, /bin/kill тоже можно использовать для того чтобы передать сигнал SIGSTOP, но внешняя программа не умеет обращаться с номером задания, ей подавай PID.
В линуксе еще достаточно удобно: 4-5 значный PID (2 байта), но в AIX-е pid-ы в основном 8значные PIDы, а могут иметь и 9 цифр, к тому же не последовательны, а разбросаны по своему 4байтному диапазону.

Сигнал SIGSTOP — это один из трех сигналов которые приложение не может игнорировать (SIGSTOP, SIGCONT, SIGKILL который обычно 9). Да, конечно у каждого из них есть и числовой код (например kill -9 означает kill -SIGKILL), но не на всех платформах они совпадают. Узнать их соответствие можно или из документации (man signal/man 7 signal/man kill), или прямо (внутренней)командой kill -l.

Завершение задания

Аналогично:
kill -SIGKILL %1 или PID процесса.

Запуск приостановленного ранее

bg %1 — отправка приостановленного задания выполняться в фон.
fg %1 — переключение в остановленное (или запущенное задание)

Еще вариант: переключиться в это задание и остановить его Ctrl+Z:

Advanced нумерация заданий

Вот у меня продолжают сжимать нули три процесса:

Первое поле в квадратных скобках — номер job-а. К нему можно обратиться такими командами как fg, bg, kill (внутренней), disown, wait.

Второе поле: имеет (минус) для 2го задания и + (плюс) для 3го — это номера заданий в нотации: «Последнее» и «Текущее».
Текущее — это то «с которым мы работаем сейчас». Если у нас запущенно одно задание — то только оно будет иметь +. Если мы переключимся на другое задание командой fg — оно станет «текущим». Команды fg и bg без номера заданий будут работать с Текущим. К нему можно также обратиться через %+ или %%

Последнее — это то, которое было перед «Текущим». Если мы завершим текущее (kill -9 %% ) — то Последнее станет Текущим. Этакий стек заданий. К нему можно обратиться через %-

Также для команд fg, bg, kill, disown, wait к заданиям можно обратиться через имя запускаемой команды:
запустим еще sleep
Убъет только одно задание, который начинается на x (у меня пострадает архивация командой xz)

убьет команду, которая содержит gzip. ( Такой процесс у меня тоже только один), а если маска такая, что в неё входит несколько заданий (например в предыдущей команда kill -9 #?zip, то такое не получится, т.к. и nice gzip и bzip2 попадают под такую маску, и нельзя точно определить к какому заданию относится команда. Хотя странно: для fg то еще можно понять что нужен один аргумент, а kill может принимать несколько аргументов, bg не может но мог бы, но в общем все команды не могут разобраться c неоднозначными масками)

Подробнее смотрите таблицу из ABS Guide

enable и builtin

Тут то и следует рассказать о командах enable и builtin:
Из ссылки выше:

Конструкция builtin BUILTIN_COMMAND запускает внутреннюю команду «BUILTIN_COMMAND», на время запрещая использование функций и внешних системных команд с тем же именем.

enable Либо запрещает, либо разрешает вызов внутренних команд. Например, enable -n kill запрещает использование внутренней команды kill, в результате, когда интерпретатор встретит команду kill, то он вызовет внешнюю команду kill, т.е. /bin/kill.

Внутренние команды вызываются быстрее чем внешние, полноценные программы, хотя бы потому, что нет необходимости форкать дочерний процесс, переключаться между ними. Список внутренних команд можно посмотреть enable -a.

Ожидание завершения фоновых задач

Команда wait — приостанавливает работу сценария до тех пор пока не будут завершены все фоновые задания или пока не будет завершено задание/процесс с указанным номером задания/PID процесса. Возвращает код завершения указанного задания/процесса.
Часто используется для синхронизации процессов: запустить один или несколько задач в фоне (параллельно), дождаться их завершения, и продолжить следующую фазу.

Запустит одновременно закачку по списку всех url, и только когда будет завершатся все закачки — перекинет их на флешку.

Команда disown

disown — Удаляет задание из таблицы активных заданий командной оболочки. Т.е. процесс продолжает работать в фоновом режиме, но уже не является заданием.
Полезно процессам запущенных командой nohup — она перехватывает сигнал SIGHUP, а также забирает потоки вывода к себе в файл nohup.out.

Также есть команды: suspend, times и logout, и times.
Например times %N — выводит накопленное время в userspace и system для job-а и текущей оболочки. Suspend приостаналивает текущую оболочку, как это можно было бы сделать нажав ctrl+Z для другой команды, но при условии что текущая оболочка работает не в режиме login shell. Но даже не представляю как их можно применять.

Источник

Linux / Unix: jobs Command Examples

I am new Linux and Unix user. How do I show the active jobs on Linux or Unix-like systems using BASH/KSH/TCSH or POSIX based shell? How can I display status of jobs in the current session on Unix/Linux?

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

Job control is nothing but the ability to stop/suspend the execution of processes (command) and continue/resume their execution as per your requirements. This is done using your operating system and shell such as bash/ksh or POSIX shell.

jobs command details
Description Show the active jobs in shell
Category Processes Management
Difficulty Easy
Root privileges No
Est. reading time 3 minutes
Table of contents
  • » Syntax
  • » Examples
  • » Show process IDs
  • » Show only jobs that have exited since last notified
  • » Show process IDs only
  • » Only show running jobs
  • » Only show stopped jobs
  • » Options
  • » Video
  • » See also

Purpose

Displays status of jobs in the current shell session.

Syntax

The basic syntax is as follows:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

jobs [options] jobID

Starting few jobs for demonstration purpose

Before you start using jobs command, you need to start couple of jobs on your system. Type the following commands to start jobs:

Finally, run ping command in foreground:

To suspend ping command job hit the Ctrl-Z key sequence.

jobs command examples

To display the status of jobs in the current shell, enter:
$ jobs
Sample outputs:

To display the process ID or jobs for the job whose name begins with “p,” enter:
$ jobs -p %p
OR
$ jobs %p
Sample outputs:

The character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping .

How do I show process IDs in addition to the normal information?

Pass the -l (lowercase L) option to jobs command for more information about each job listed, run:
$ jobs -l
Sample outputs:

Fig.01: Displaying the status of jobs in the shell

How do I list only processes that have changed status since the last notification?

First, start a new job as follows:
$ sleep 100 &
Now, only show jobs that have stopped or exited since last notified, type:
$ jobs -n
Sample outputs:

Display lists process IDs (PIDs) only

Pass the -p option to jobs command to display PIDs only:
$ jobs -p
Sample outputs:

How do I display only running jobs?

Pass the -r option to jobs command to display only running jobs only, type:
$ jobs -r
Sample outputs:

How do I display only jobs that have stopped?

Pass the -s option to jobs command to display only stopped jobs only, type:
$ jobs -s
Sample outputs:

To resume the ping cyberciti.biz job by entering the following bg command:
$ bg %4

jobs command options

Table 1: From the bash(1) command man page:
Option Description
-l Show process id’s in addition to the normal information.
-p Show process id’s only.
-n Show only processes that have changed status since the last notification are printed.
-r Restrict output to running jobs only.
-s Restrict output to stopped jobs only.
-x COMMAND is run after all job specifications that appear in ARGS have been replaced with the process ID of that job’s process group leader./td>

A note about /usr/bin/jobs and shell builtin

Type the following type command/command command to find out whether jobs is part of shell, external command or both:
$ type -a jobs
$ command -V jobs
Sample outputs:

In almost all cases you need to use the jobs command that is implemented as a BASH/KSH/POSIX shell built-in. The /usr/bin/jobs command can not be used in the current shell. The /usr/bin/jobs command operates in a different environment and does not share the parent bash/ksh’s shells understanding of jobs.

This tutorials is also available in a quick video format:

You learned about jobs command on Linux and Unix-like systems. See also:

  • bash(1) Linux/Unix command man page

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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