- Есть остановленные задания (при выходе из bash)
- 2 ответа
- Starting Stopped Jobs in Ubuntu Linux
- Listing Stopped Jobs
- Starting Jobs
- Stopping Jobs
- Logging Out
- Upstart Jobs
- Starting Jobs in the Background
- There are stopped jobs (on bash exit)
- 2 Answers 2
- How can I kill all stopped jobs?
- 8 Answers 8
- Linux / Unix: jobs Command Examples
- Purpose
- Syntax
- Starting few jobs for demonstration purpose
- jobs command examples
- How do I show process IDs in addition to the normal information?
- How do I list only processes that have changed status since the last notification?
- Display lists process IDs (PIDs) only
- How do I display only running jobs?
- How do I display only jobs that have stopped?
- jobs command options
- A note about /usr/bin/jobs and shell builtin
- Related media
Есть остановленные задания (при выходе из bash)
Я получаю сообщение There are stopped jobs. . Вот воспроизводимый сценарий в python 2.x:
- ctrl + c обрабатывается интерпретатором как исключение.
- ctrl + z «останавливает» процесс.
- ctrl + d завершает работу python для реалов.
Вот какой-то реальный вывод терминала:
Bash не вышел, я должен exit снова, чтобы выйти из оболочки bash.
- Q: Что такое «остановленная работа» или что это означает?
- Q: Можно ли возобновить приостановленный процесс?
- Q: Выключает ли первый exit остановленные задания?
- Q: Есть ли способ выйти из оболочки в первый раз? (без ввода exit дважды)
2 ответа
Задержанное задание — это тот, который был временно помещен в фоновый режим и больше не работает, но все еще использует такие ресурсы (например, системную память). Поскольку это задание не подключено к текущему терминалу, оно не может выдавать выходные данные и не получает вход от пользователя.
Вы можете видеть задания, которые выполнялись с помощью команды jobs builtin в bash, возможно, других оболочек. Пример:
Вы можете возобновить остановленное задание с помощью встроенной команды bash fg (foreground) bash. Если у вас несколько остановленных команд, вы должны указать, какой из них нужно возобновить, передав номер задания в командной строке с помощью fg . Если только одна программа остановлена, вы можете использовать только fg :
В этот момент вы вернулись в интерпретатор python и можете выйти с помощью control-D.
И наоборот, вы можете kill команду с ее спецификацией jobs или PID. Например:
Чтобы использовать спецификацию jobs, перед номером с помощью клавиши процента (%):
Если вы выдаете команду exit с остановленными заданиями, будет выдано предупреждение. Работы будут оставлены для обеспечения безопасности. Это необходимо, чтобы вы знали, что пытаетесь убить задания, о которых вы, возможно, забыли, остановились. Во второй раз, когда вы используете команду exit, задания завершаются и оболочка завершается. Это может вызвать проблемы для некоторых программ, которые не предназначены для убийства таким образом.
В bash, кажется, вы можете использовать команду logout , которая будет убивать остановленные процессы и завершать работу. Это может привести к нежелательным результатам.
Также обратите внимание, что некоторые программы не могут выйти при завершении таким образом, и ваша система может закончиться большим количеством сиротских процессов, используя ресурсы, если вы привыкли делать это.
Обратите внимание, что вы можете создать фоновый процесс, который остановится, если он потребует ввода пользователем:
Вы можете возобновить и убить эти задания так же, как и задания, которые вы остановили с помощью прерывания Ctrl-z .
В: Что такое «остановленная работа» или что это означает?
Остановленное задание означает процесс, который получил сигнал останова ( SIGSTOP / SIGTSTP ) с клавиатуры (suspend character Ctrl-Z ), команда (например, kill -STOP [PID] ) или другой процесс (например, ядро, когда системе не хватает ресурсов), и он находится в состоянии паузы, поэтому он сообщает системе прекратить /приостановить процесс, чтобы он не выполнял любое выполнение /обработка.
Активные задания оболочки могут быть перечислены: jobs .
В: Может ли возобновленный процесс возобновиться?
Прекращенный процесс возобновит выполнение, только если он отправит сигнал SIGCONT . Это может быть достигнуто либо с помощью fg (или fg ID )), который переместит задание на передний план, сделав его текущим заданием, bg , чтобы продолжить это в фоновом режиме или путем отправки сигнала SIGCONT (например, kill -CONT [PID] )).
Q: Первый выход убил остановленные задания?
В первый раз, когда вы вводите exit / logout или нажмите Ctrl-D , оболочка печатает предупреждающее сообщение о текущих активных заданиях, которые связанный с вашим терминалом, поэтому он не убьет вас без вашего разрешения, подтвердив действие во второй раз. Если параметр checkjobs включен ( shopt -s checkjobs ), он также может отображать задания со своими статусами.
Q: Есть ли способ выйти из оболочки в первый раз? (без двойного выхода)
Вы можете нажать Ctrl + D дважды, или удерживать его дольше, это приведет к выходу из оболочки тихо, быстро убив текущие остановленные /выполняемые задания.
Альтернативно отключите их ( disown ), чтобы оставить их или убить их вручную: kill $(jobs -p) .
Источник
Starting Stopped Jobs in Ubuntu Linux
Listing Stopped Jobs
Type the “jobs” command at a terminal prompt and press “Enter” to view information about stopped, running and terminated jobs for your current user session. The jobs command displays information about the jobs in three columns. The first column contains the job’s number, the second column contains the job’s status and the last column contains the command the job is running.
A job’s status can be either “Running” if it’s currently running, “Stopped” if it’s stopped or “Killed” if you’ve terminated it.
You can use the number displayed in the first column to perform actions on a specific job, such as starting it in the background, starting it in the foreground or terminating it.
Starting Jobs
You can type “fg” into the Ubuntu terminal and press “Enter” to start the most recently stopped job in the foreground. A job started in the foreground displays its output in the terminal window. You can also type “bg” instead to start the most recently stopped job in the background. A job running in the background doesn’t display any output in the terminal, leaving your terminal session free to perform other commands.
You can also use the “fg” or “bg” commands to start specific jobs in the foreground or background. Type “fg %1” or “bg %1” into the terminal to start a stopped job in the foreground or background, replacing “1” with the number of the stopped job from the jobs command, and press “Enter.”
Stopping Jobs
Once the job is started in the foreground, you can stop it again by pressing the “Ctrl” and “Z” keys on your keyboard at the same time, or terminate it entirely by pressing the “Ctrl” and “C” keys on your keyboard at the same time.
If a job is running in the background, you can use the “fg %1” command to bring it to the foreground, replacing “1” with the number of the job from the jobs command.
You can terminate a job with the kill command. Type “kill -9 %1” into the terminal, replacing “1” with the job’s number from the jobs command, and press “Enter” to kill the job. You’ll lose any open data the job hasn’t saved yet because the “kill -9” command forcibly terminates processes without allowing them to save any open data.
Logging Out
If you type the “logout” or “exit” commands into a terminal and receive the “There are stopped jobs” message, you don’t have to stop the jobs before logging out. This is a confirmation method to remind you that there are stopped jobs you will lose if you log out. You can continue with the log-out process and forcibly terminate the stopped jobs by typing the “logout” command into the terminal again and pressing “Enter” without typing the “jobs” command in between to list the stopped jobs. If you type the “jobs” command in between, you’ll have to type the “logout” command twice.
Upstart Jobs
Ubuntu also includes the Upstart daemon, which replaces the traditional init daemon and manages the services running in the background on your Ubuntu system. Upstart also refers to the services installed on the system as jobs. You can use the “start” and “stop” commands to start stopped services and stop running services.
Type “sudo start service” into the terminal window, replacing “service” with the name of the stopped Upstart job you want to start, and press “Enter” to start a stopped upstart Job. You can also use the “sudo stop service” command to stop a running service.
The sudo command will prompt you for your password. Type it at the password prompt and press “Enter” to authenticate.
If you don’t know the exact name of the Upstart job you want to start, you can type “ls /etc/init.d” into the terminal and press “Enter” to see a list of Upstart jobs stored in the init.d directory.
Starting Jobs in the Background
By default, any command you type in the terminal runs as a foreground job. You can directly run a command as a background job by appending it with a space and an ampersand, such as “firefox &” to run Firefox as a background job. The Firefox browser window will open on your desktop, but your terminal won’t show Firefox’s status messages.
Источник
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 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:
Источник
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?
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
|
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
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.
Related media
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
Источник