- jobs
- DESCRIPTION
- OPTIONS
- OPERANDS
- STDIN
- INPUT FILES
- ENVIRONMENT VARIABLES
- ASYNCHRONOUS EVENTS
- STDOUT
- STDERR
- OUTPUT FILES
- EXTENDED DESCRIPTION
- EXIT STATUS
- CONSEQUENCES OF ERRORS
- APPLICATION USAGE
- EXAMPLES
- RATIONALE
- FUTURE DIRECTIONS
- COPYRIGHT
- SEE ALSO
- Linux jobs
- Linux jobs и команды по управлению ими
- Linux Commands: jobs, bg, and fg
- Jobs
- Background
- Foreground
- The end
jobs
This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
DESCRIPTION
The jobs utility shall display the status of jobs that were started in the current shell environment; see Section 2.12, Shell Execution Environment.
When jobs reports the termination status of a job, the shell shall remove its process ID from the list of those «known in the current shell execution environment»; see Section 2.9.3.1, Examples.
OPTIONS
The jobs utility shall conform to the Base Definitions volume of POSIX.1‐2017, Section 12.2, Utility Syntax Guidelines.
The following options shall be supported:
(The letter ell.) Provide more information about each job listed. This information shall include the job number, current job, process group ID, state, and the command that formed the job.
Display only the process IDs for the process group leaders of the selected jobs.
By default, the jobs utility shall display the status of all stopped jobs, running background jobs and all jobs whose status has changed and have not been reported by the shell.
OPERANDS
The following operand shall be supported:
Specifies the jobs for which the status is to be displayed. If no job_id is given, the status information for all jobs shall be displayed. The format of job_id is described in the Base Definitions volume of POSIX.1‐2017, Section 3.204, Job Control Job ID.
STDIN
INPUT FILES
ENVIRONMENT VARIABLES
The following environment variables shall affect the execution of jobs:
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1‐2017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
If set to a non-empty string value, override the values of all the other internationalization variables.
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
Determine the location of message catalogs for the processing of LC_MESSAGES.
ASYNCHRONOUS EVENTS
STDOUT
If the -p option is specified, the output shall consist of one line for each process ID:
Otherwise, if the -l option is not specified, the output shall be a series of lines of the form:
where the fields shall be as follows:
The character ‘+’ identifies the job that would be used as a default for the fg or bg utilities; this job can also be specified using the job_id %+ or «%%». The character ‘-‘ identifies the job that would become the default if the current default job were to exit; this job can also be specified using the job_id %-. For other jobs, this field is a . At most one job can be identified with ‘+’ and at most one job can be identified with ‘-‘. If there is any suspended job, then the current job shall be a suspended job. If there are at least two suspended jobs, then the previous job also shall be a suspended job.
A number that can be used to identify the process group to the wait, fg, bg, and kill utilities. Using these utilities, the job can be identified by prefixing the job number with ‘%’.
One of the following strings (in the POSIX locale):
Indicates that the job has not been suspended by a signal and has not exited.
Indicates that the job completed and returned exit status zero.
Indicates that the job completed normally and that it exited with the specified non-zero exit status, code, expressed as a decimal number.
Indicates that the job was suspended by the SIGTSTP signal.
Indicates that the job was suspended by the SIGTSTP signal.
Indicates that the job was suspended by the SIGSTOP signal.
Indicates that the job was suspended by the SIGTTIN signal.
Indicates that the job was suspended by the SIGTTOU signal.
The implementation may substitute the string Suspended in place of Stopped. If the job was terminated by a signal, the format of state> is unspecified, but it shall be visibly distinct from all of the other state> formats shown here and shall indicate the name or description of the signal causing the termination.
The associated command that was given to the shell.
If the -l option is specified, a field containing the process group ID shall be inserted before the state> field. Also, more processes in a process group may be output on separate lines, using only the process ID and command> fields.
STDERR
The standard error shall be used only for diagnostic messages.
OUTPUT FILES
EXTENDED DESCRIPTION
EXIT STATUS
The following exit values shall be returned:
CONSEQUENCES OF ERRORS
The following sections are informative.
APPLICATION USAGE
The -p option is the only portable way to find out the process group of a job because different implementations have different strategies for defining the process group of the job. Usage such as $( jobs -p) provides a way of referring to the process group of the job in an implementation-independent way.
The jobs utility does not work as expected when it is operating in its own utility execution environment because that environment has no applicable jobs to manipulate. See the APPLICATION USAGE section for bg . For this reason, jobs is generally implemented as a shell regular built-in.
EXAMPLES
RATIONALE
Both «%%» and «%+» are used to refer to the current job. Both forms are of equal validity—the «%%» mirroring «$$» and «%+» mirroring the output of jobs. Both forms reflect historical practice of the KornShell and the C shell with job control.
The job control features provided by bg, fg, and jobs are based on the KornShell. The standard developers examined the characteristics of the C shell versions of these utilities and found that differences exist. Despite widespread use of the C shell, the KornShell versions were selected for this volume of POSIX.1‐2017 to maintain a degree of uniformity with the rest of the KornShell features selected (such as the very popular command line editing features).
The jobs utility is not dependent on the job control option, as are the seemingly related bg and fg utilities because jobs is useful for examining background jobs, regardless of the condition of job control. When the user has invoked a set +m command and job control has been turned off, jobs can still be used to examine the background jobs associated with that current session. Similarly, kill can then be used to kill background jobs with kill %background job number>.
The output for terminated jobs is left unspecified to accommodate various historical systems. The following formats have been witnessed:
signal name( coredump)
signal description— core dumped
Most users should be able to understand these formats, although it means that applications have trouble parsing them.
The calculation of job IDs was not described since this would suggest an implementation, which may impose unnecessary restrictions.
In an early proposal, a -n option was included to «Display the status of jobs that have changed, exited, or stopped since the last status report». It was removed because the shell always writes any changed status of jobs before each prompt.
FUTURE DIRECTIONS
COPYRIGHT
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology — Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
SEE ALSO
Section 2.12, Shell Execution Environment, bg , fg , kill , wait The Base Definitions volume of POSIX.1‐2017, Section 3.204, Job Control Job ID, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines
Linux jobs
Linux jobs — системные задания, которые создаются пользователем в неограниченных количествах с возможностью переключения от одного к другому (с переднего на задний план и в обратном направлении).
Работа всегда производится с тем заданием, которое находится на переднем плане (foreground).
Linux jobs и команды по управлению ими
CTRL+Z работает с большинством процессов — переводит их в подвешенное состояние — останавливает и отправляет на задний план.
Все остановленные команды можно посмотреть введя в терминале jobs
Сейчас выполняются оба находясь при этом в фоне:
[1]- Stopped ping ya.ru
[2]+ Stopped top
Теперь можно переместить одно из заданий на передний план указав его номер
ping ya.ru
64 bytes from www.yandex.ru (93.158.134.3): icmp_seq=4 ttl=57 time=30.3 ms
64 bytes from www.yandex.ru (93.158.134.3): icmp_seq=5 ttl=57 time=29.0 ms
При переводе на передний план вывод производится в основной терминал, более ничего не меняется и задание выполняется в любом случае
Можно таким же образом вывести команду на задний план
Вывод команды таким образом продолжит быть присоединенным к терминалу, результат tail -f снова выведется в консоль как только в лог будет записываться информация (сэмулировать ситуацию можно перезапустив какой-либо демон подключившись к системе через другой терминал).
При выполнении в bg таким образом для нескольких команд их вывод в терминал будет смешиваться случайным образом, что может быть не очень удобно.
Если запустить команду со знаком амперсанда изначально она будет отображаться в выводе jobs как выполняющийся процесс со статусом Running.
Пример приведен на скриншоте:
Удалить процесс можно указывая его номер со знаком процента
Работа с Linux jobs является типичной операцией поручному управлению системными процессами. Читайте подробнее про управление процессами и ps aux
Linux Commands: jobs, bg, and fg
In this quick tutorial, I want to look at the jobs command and a few of the ways that we can manipulate the jobs running on our systems. In short, controlling jobs lets you suspend and resume processes started in your Linux shell.
Jobs
The jobs command will list all jobs on the system; active, stopped, or otherwise. Before I explore the command and output, I’ll create a job on my system.
I will use the sleep job as it won’t change my system in any meaningful way.
[tcarrigan@rhel ~]$ sleep 500 ^Z [1]+ Stopped sleep 500
First, I issued the sleep command, and then I received the Job number [1]. I then immediately stopped the job by using Ctl+Z. Next, I run the jobs command to view the newly created job:
[tcarrigan@rhel ~]$ jobs [1]+ Stopped sleep 500
You can see that I have a single stopped job identified by the job number [1].
Other options to know for this command include:
- -l — list PIDs in addition to default info
- -n — list only processes that have changed since the last notification
- -p — list PIDs only
- -r — show only running jobs
- -s — show only stopped jobs
Background
Next, I’ll resume the sleep job in the background. To do this, I use the bg command. Now, the bg command has a pretty simple syntax, as seen here:
Where JOB_SPEC can be any of the following:
- %n — where n is the job number
- %abc — refers to a job started by a command beginning with abc
- %?abc — refers to a job started by a command containing abc
- %- — specifies the previous job
NOTE: bg and fg operate on the current job if no JOB_SPEC is provided.
I can move this job to the background by using the job number [1].
[tcarrigan@rhel ~]$ bg %1 [1]+ sleep 500 &
You can see now that I have a single running job in the background.
[tcarrigan@rhel ~]$ jobs [1]+ Running sleep 500 &
Foreground
Now, let’s look at how to move a background job into the foreground. To do this, I use the fg command. The command syntax is the same for the foreground command as with the background command.
Refer to the above bullets for details on JOB_SPEC.
I have started a new sleep in the background:
[tcarrigan@rhel ~]$ sleep 500 & [2] 5599
Now, I’ll move it to the foreground by using the following command:
[tcarrigan@rhel ~]$ fg %2 sleep 500
The fg command has now brought my system back into a sleep state.
The end
While I realize that the jobs presented here were trivial, these concepts can be applied to more than just the sleep command. If you run into a situation that requires it, you now have the knowledge to move running or stopped jobs from the foreground to background and back again.