you have stopped jobs что делать
What should I do when I get ‘There are stopped jobs’ error?
I face this type of situation many times.
For example, whenever I try to open some file in emacs with sudo rights using:
Instead of asking me for the password Ubuntu just starts emacs process without any emacs window or any output on terminal (except for the pid) see the image (if I don’t use ‘&’ then it will ask me for the password):
I have two questions related with this:
What should I do when I get error that ‘There are stopped jobs’? How do I identify all such stopped jobs and kill them? Once I clear the terminal I won’t have pids of these stopped processes.
Why is Ubuntu/emacs behaving like this? Why doesn’t it ask me for the password?
3 Answers 3
There are stopped jobs message is far, far away to be an error. It’s just a notification telling you that you attempt to exit from the shell, but you have one or more suspended jobs/programs (in your case emacs which you putted in background using & at the end of your command). The system doesn’t let you to exit from the shell and kill the jobs unless you mean to. You can do a couple of things in response to this message:
To answer the second question, I will tell you that not Ubuntu or emacs behaving like this. This is a normal behavior when you put an application to run in background. In this case sudo is asking for password, but is asking in background, so you can’t see this fact. To see it, you should bring back the job in foreground using fg command:
After this you can type Ctrl + Z to put again the job in background if you want. Then you can run again ‘fg’ command to bring back the job in foreground and so on.
Управление заданиями
Наверное всякий 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-ами.
Остановка заданий
Приостановка
Приостанвим задание, например первое:
это сделает команда kill, передавая сигнал SIGSTOP.
В данном случае использовалась внутренняя команда bash-а: kill, а не внешняя программа /bin/kill.
Да, /bin/kill тоже можно использовать для того чтобы передать сигнал SIGSTOP, но внешняя программа не умеет обращаться с номером задания, ей подавай PID.
В линуксе еще достаточно удобно: 4-5 значный PID (2 байта), но в AIX-е pid-ы в основном 8значные PIDы, а могут иметь и 9 цифр, к тому же не последовательны, а разбросаны по своему 4байтному диапазону.
Завершение задания
Запуск приостановленного ранее
bg %1 — отправка приостановленного задания выполняться в фон.
fg %1 — переключение в остановленное (или запущенное задание)
Еще вариант: переключиться в это задание и остановить его Ctrl+Z:
Advanced нумерация заданий
Вот у меня продолжают сжимать нули три процесса:
Первое поле в квадратных скобках — номер job-а. К нему можно обратиться такими командами как fg, bg, kill (внутренней), disown, wait.
Второе поле: имеет — (минус) для 2го задания и + (плюс) для 3го — это номера заданий в нотации: «Последнее» и «Текущее».
Текущее — это то «с которым мы работаем сейчас». Если у нас запущенно одно задание — то только оно будет иметь +. Если мы переключимся на другое задание командой fg — оно станет «текущим». Команды fg и bg без номера заданий будут работать с Текущим. К нему можно также обратиться через %+ или %%
Также для команд fg, bg, kill, disown, wait к заданиям можно обратиться через имя запускаемой команды:
запустим еще sleep
Убъет только одно задание, который начинается на x (у меня пострадает архивация командой xz)
Подробнее смотрите таблицу из ABS Guide
enable и builtin
Тут то и следует рассказать о командах enable и builtin:
Из ссылки выше:
Конструкция builtin BUILTIN_COMMAND запускает внутреннюю команду «BUILTIN_COMMAND», на время запрещая использование функций и внешних системных команд с тем же именем.
Ожидание завершения фоновых задач
Команда wait — приостанавливает работу сценария до тех пор пока не будут завершены все фоновые задания или пока не будет завершено задание/процесс с указанным номером задания/PID процесса. Возвращает код завершения указанного задания/процесса.
Часто используется для синхронизации процессов: запустить один или несколько задач в фоне (параллельно), дождаться их завершения, и продолжить следующую фазу.
Запустит одновременно закачку по списку всех url, и только когда будет завершатся все закачки — перекинет их на флешку.
Команда disown
disown — Удаляет задание из таблицы активных заданий командной оболочки. Т.е. процесс продолжает работать в фоновом режиме, но уже не является заданием.
Полезно процессам запущенных командой nohup — она перехватывает сигнал SIGHUP, а также забирает потоки вывода к себе в файл nohup.out.
Также есть команды: suspend, times и logout, и times.
Например times %N — выводит накопленное время в userspace и system для job-а и текущей оболочки. Suspend приостаналивает текущую оболочку, как это можно было бы сделать нажав ctrl+Z для другой команды, но при условии что текущая оболочка работает не в режиме login shell. Но даже не представляю как их можно применять.
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:
Here is some real-world terminal output:
Bash did not exit, I must exit again to exit the bash shell.
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:
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.
Thread: What to do about the «stopped jobs» while closing a terminal?
Thread Tools
Display
What to do about the «stopped jobs» while closing a terminal?
When my work is completed, I generally press ctrl+D to close my terminal. Sometimes I get a comment that «there are stopped jobs» and the terminal is not closed. If I press ctrl+D again, the same comment may appear or sometimes the terminal is closed. Why does this happen? Does this mean that I made a mistake in closing some application? How to rectify that at this stage?
Re: What to do about the «stopped jobs» while closing a terminal?
Take a look at post.#4 of this thread.
You can list the stopped jobs by doing:
Re: What to do about the «stopped jobs» while closing a terminal?
However I am not sure if this way of killing a job by issuing a command (kill %jobno.) is harmful or not. Now a days I am using a newly installed mathematics program where even after exiting it, I am getting the «there are stopped jobs» warning at the time of exiting terminal. I am a bit suspicious; exiting a program suitably should completely stop all the related processes. Now if some of these remain alive even after exiting and I «kill» those processes, will it not be harmful for the computer in the long run?
If we simply switch off the UPS, the computer will obviously stop but that is not the way we do. We «shut down» the machine and the machine stops after all the running processes are sequentially stopped. Switching off the machine will severely affect the machine in the long run. May be I am messing up things but can anybody please clarify?
Re: What to do about the «stopped jobs» while closing a terminal?
I’m pretty sure that ‘kill’ just sends a signal to the program to close, it doesn’t force it shut immediately but rather allows it to shut down gracefully.
Re: What to do about the «stopped jobs» while closing a terminal?
Still I’d suggest you look into why you have those stopped jobs. Perhaps they are child processes spawned by your math program. Do they only happen when you use this program? What happens if you type «fg» at the prompt after the «there are stopped jobs» error?



С Юниксом на vi
СЕРГЕЙ СУПРУНОВ