How to resume process linux

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.

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.

Источник

Основы Linux от основателя Gentoo. Часть 2 (3/5): Управление процессами

В этом отрывке рассмотрены команды управления процессами. Вы научитесь замораживать процессы, размораживать, отправлять в фоновый режим, изменять приоритет, просматривать запущенные процессы и жестоко их убивать. Введено понятие сигналов. Рассмотрены такие команды, как bg, fg, jobs, kill, nohup, nice, renice, ps и top.

Навигация по основам Linux от основателя Gentoo:
Часть I
  1. BASH: основы навигации (вступление)
  2. Управление файлами и директориями
  3. Ссылки, а также удаление файлов и директорий
  4. Glob-подстановки (итоги и ссылки)

Часть II

Управление процессами

Запуск xeyes

Для изучения управления процессами, какой-нибудь процесс необходимо сначала запустить. Убедитесь, что у вас запущен X (графический сервер — прим. пер.) и выполните следующую команду:

$ xeyes -center red

Вы увидите всплывающее окошко xeyes и красные глаза, следящие за курсором мыши. Также, обратите внимание, что у вас не появилось приглашения для ввода команд в терминале.

Остановка процесса

Чтобы вернуть приглашение, вы должны нажать Control-C (часто пишется как Ctrl-C или ^C):

Читайте также:  Linux запуск скрипта с рабочего стола

Вы получили назад свое приглашение, но и окно xeyes исчезло. Фактически, процесс был «убит». Вместо завершения по Control-C, мы можем просто остановить процесс с помощью Control-Z:

На этот раз вы получите приглашение bash’a, а окно xeyes останется сверху. Если вы с ним немного поиграете, возможно заметите, что глаза заморожены на одном месте. Если окно xeyes будет перекрыто другим окном и затем снова открыто, вы увидите, что оно даже не перерисовалось. Процесс не делает ничего. Он на самом деле остановлен.

fg и bg

Чтобы процесс «растормошить» и запустить обратно, мы можем вывести его на передний план используя команду fg (от англ. foreground — прим. пер.):

$ fg
(test it out, then stop the process again)
Control-Z
$

А теперь продолжим его в фоне с помощью команды bg (от англ. backgroud — прим. пер.):

Прекрасно! Процесс xeyes сейчас запущен в фоновом режиме, а мы снова имеем приглашение bash.

Использование «&»

Если нам нужно сразу запустить xeyes в фоновом режиме (вместо использования Control-Z и bg), мы можем просто добавить «&amp» (амперсанд) в конец команды xeyes:

$ xeyes -center blue &amp
[2] 16224

Несколько фоновых процессов

Теперь в фоне у нас одновременно работают красные и синие xeyes. Мы можем просмотреть список заданий с помощью jobs:

Число в левой колонке — это порядковый номер задания, который bash присваивает ему при запуске. Плюс (+) у второго задания значит, что это «текущее задание», оно будет выведено на передний план при вводе fg. Вы также можете вывести на передний план конкретное задание указывая его номер; например, fg 1 сделает таковым красный xeyes. Следующая колонка это идентификатор процесса или сокращенно pid, любезно добавленный в вывод благодаря опции -l. Наконец, состояние обоих процессов «Running» (выполняется) и их командная строка справа.

Введение в сигналы

Чтобы убить, остановить, или продолжить процесс, Linux использует специальную форму взаимодействия, называемую сигналы. Отправляя сигнал некоторому процессу, вы можете его завершить, остановить, или сделать что-нибудь еще. Это то, что происходит на самом деле, когда вы нажимаете Control-C, Control-Z, или используете bg и fg — вы указываете bash отправить процессу определенный сигнал. Сигналы также можно отправить с помощью команды kill указав ей как параметр id процесса (pid):

Как можно заметить, kill не обязательно «убивает» процесс, хотя может и это. Используя опцию -s, kill может отправить процессу любой сигнал. Linux убивает, останавливает или продолжает процессы когда они получают SIGINT, SIGSTOP, или SIGCONT сигнал соответственно. Есть и другие сигналы, которые вы можете отправить процессам; некоторые сигналы могут обрабатываться внутри самих программ. Вы можете узнать о сигналах которые обрабатывает конкретная программа поискав в ее man’е секцию SIGNALS.

SIGTERM и SIGINT

Если вы хотите убить процесс, есть несколько вариантов. По-умолчанию, kill отправляет SIGTERM, который отличается от SIGINT отправляемого по Control-C, но обычно имеет тот же эффект:

Полное убийство

Процесс может игнорировать оба сигнала, SIGTERM и SIGINT, либо по своему усмотрению, либо потому, что он остановлен, либо еще как-то «застрял». В этом случае, может быть необходимо использование большого молотка — сигнала SIGKILL. Процесс не может игнорировать SIGKILL:

nohup

Терминал в котором вы запускаете задания, называется терминалом управления заданиями. Некоторые шеллы (но не bash по-умолчанию), отправляют сигнал SIGHUP фоновым заданиям когда вы выходите, заставляя их завершаться. Для защиты процессов от такого поведения, используйте nohup когда запускаете процесс:

Используем ps для вывода списка процессов

Команда jobs, которую мы использовали ранее выводит только те процессы, которые были запущены в вашей сессии bash. Чтобы увидеть все процессы в вашей системе, используйте ps совместно с опциями a и x:

Здесь приведены только первые 5 процессов, поскольку обычно список процессов очень длинный. Команда дает вам «слепок» всего, что в данный момент выполняется на машине, однако в нем много лишней информации. Если бы вы, не указали ax, вы бы получили список только тех процессов, которые принадлежат вам, и которые есть в управляющем терминале. Команда ps x покажет все ваши процессы, даже те, которых нет в управляющем терминале. Если использовать ps a, то будет получен список процессов из терминалов всех пользователей.

Просмотр «леса» и «деревьев»

Вы также можете просмотреть и другую информацию о каждом процессе. Опция —forest позволяет легко просмотреть иерархию процессов и даст вам представление о том, как различные процессы в системе взаимосвязаны между собой. Если один процесс запускает другой процесс, то запущенный будет называться его потомком. В выводе —forest, родители находятся слева, а потомки появляются как ветки справа:

«u» и «l» опции ps

Опции u и l могут быть использованы в любой комбинации с опциями a, x с целью получения более подробной информации о процессах:

Использование top

Если вы обнаружили, что запускаете ps несколько раз подряд, пытаясь рассмотреть происходящие изменения, возможно вам стоит воспользоваться top. Программа top отображает постоянно обновляющийся список процессов, наряду с другой полезной информацией:

Каждый процесс имеет свое значение приоритета, которое Linux использует для разделения времени CPU. Вы можете указать приоритет процесса при его запуске, с помощью команды nice:

Читайте также:  Тема для windows дракон

$ nice -n 10 oggenc /tmp/song.wav

С тех пор, как приоритет стал называться nice, он стал легче для запоминания, так, большее значение nice делает «хорошо» (nice — хорошо, замечательно; прим. пер.) другим процессам, позволяя им получить более приоритетный доступ к времени CPU. По-умолчанию, процессы запускаются с приоритетом 0, поэтому установка приоритета в 10 для oggenc значит, что он будет давать больше времени поработать другим процессам. Как правило, это означает, что oggenc даст возможность другим процессам выполняться со своей обычной скоростью, не зависимо от того, сколько времени процессора хочет сам oggenc. Вы могли видеть эти «уровни любезности» в колонке NI у ps и top ранее.

renice

Команда nice может изменять приоритет процессов только во время их запуска. Если вам необходимо изменить приоритет работающего процесса, воспользуйтесь командой renice:

$ renice 10 641
641: old priority 0, new priority 10

Спасибо Dmitry Minsky (Dmitry.Minsky@gmail.com) за перевод.

Об авторах

Daniel Robbins

Дэниэль Роббинс — основатель сообщества Gentoo и создатель операционной системы Gentoo Linux. Дэниэль проживает в Нью-Мехико со свой женой Мэри и двумя энергичными дочерьми. Он также основатель и глава Funtoo, написал множество технических статей для IBM developerWorks, Intel Developer Services и C/C++ Users Journal.

Chris Houser

Крис Хаусер был сторонником UNIX c 1994 года, когда присоединился к команде администраторов университета Тэйлора (Индиана, США), где получил степень бакалавра в компьютерных науках и математике. После он работал во множестве областей, включая веб-приложения, редактирование видео, драйвера для UNIX и криптографическую защиту. В настоящий момент работает в Sentry Data Systems. Крис также сделал вклад во множество свободных проектов, таких как Gentoo Linux и Clojure, стал соавтором книги The Joy of Clojure.

Aron Griffis

Эйрон Гриффис живет на территории Бостона, где провел последнее десятилетие работая в Hewlett-Packard над такими проектами, как сетевые UNIX-драйвера для Tru64, сертификация безопасности Linux, Xen и KVM виртуализация, и самое последнее — платформа HP ePrint. В свободное от программирования время Эйрон предпочитает размыщлять над проблемами программирования катаясь на своем велосипеде, жонглируя битами, или болея за бостонскую профессиональную бейсбольную команду «Красные Носки».

Источник

How To Use ps, kill, and nice to Manage Processes in Linux

Published on September 6, 2013

Introduction

A Linux server, like any other computer you may be familiar with, runs applications. To the computer, these are considered “processes”.

While Linux will handle the low-level, behind-the-scenes management in a process’s life-cycle, you will need a way of interacting with the operating system to manage it from a higher-level.

In this guide, we will discuss some simple aspects of process management. Linux provides an abundant collection of tools for this purpose.

We will explore these ideas on an Ubuntu 12.04 VPS, but any modern Linux distribution will operate in a similar way.

How To View Running Processes in Linux

The easiest way to find out what processes are running on your server is to run the top command:

The top chunk of information give system statistics, such as system load and the total number of tasks.

You can easily see that there is 1 running process, and 55 processes are sleeping (aka idle/not using CPU resources).

The bottom portion has the running processes and their usage statistics.

An improved version of top , called htop , is available in the repositories. Install it with this command:

If we run the htop command, we will see that there is a more user-friendly display:

How To Use ps to List Processes

Both top and htop provide a nice interface to view running processes similar to a graphical task manager.

However, these tools are not always flexible enough to adequately cover all scenarios. A powerful command called ps is often the answer to these problems.

When called without arguments, the output can be a bit lack-luster:

This output shows all of the processes associated with the current user and terminal session. This makes sense because we are only running bash and ps with this terminal currently.

To get a more complete picture of the processes on this system, we can run the following:

These options tell ps to show processes owned by all users (regardless of their terminal association) in a user-friendly format.

To see a tree view, where hierarchal relationships are illustrated, we can run the command with these options:

As you can see, the process kthreadd is shown to be a parent of the ksoftirqd/0 process and the others.

A Note About Process IDs

In Linux and Unix-like systems, each process is assigned a process ID, or PID. This is how the operating system identifies and keeps track of processes.

A quick way of getting the PID of a process is with the pgrep command:

This will simply query the process ID and return it.

The first process spawned at boot, called init, is given the PID of “1”.

This process is then responsible for spawning every other process on the system. The later processes are given larger PID numbers.

Читайте также:  Windows download from ftp

A process’s parent is the process that was responsible for spawning it. Parent processes have a PPID, which you can see in the column headers in many process management applications, including top , htop and ps .

Any communication between the user and the operating system about processes involves translating between process names and PIDs at some point during the operation. This is why utilities tell you the PID.

Parent-Child Relationships

Creating a child process happens in two steps: fork(), which creates new address space and copies the resources owned by the parent via copy-on-write to be available to the child process; and exec(), which loads an executable into the address space and executes it.

In the event that a child process dies before its parent, the child becomes a zombie until the parent has collected information about it or indicated to the kernel that it does not need that information. The resources from the child process will then be freed. If the parent process dies before the child, however, the child will be adopted by init, though it can also be reassigned to another process.

How To Send Processes Signals in Linux

All processes in Linux respond to signals. Signals are an os-level way of telling programs to terminate or modify their behavior.

How To Send Processes Signals by PID

The most common way of passing signals to a program is with the kill command.

As you might expect, the default functionality of this utility is to attempt to kill a process:

This sends the TERM signal to the process. The TERM signal tells the process to please terminate. This allows the program to perform clean-up operations and exit smoothly.

If the program is misbehaving and does not exit when given the TERM signal, we can escalate the signal by passing the KILL signal:

This is a special signal that is not sent to the program.

Instead, it is given to the operating system kernel, which shuts down the process. This is used to bypass programs that ignore the signals sent to them.

Each signal has an associated number that can be passed instead of the name. For instance, You can pass “-15” instead of “-TERM”, and “-9” instead of “-KILL”.

How To Use Signals For Other Purposes

Signals are not only used to shut down programs. They can also be used to perform other actions.

For instance, many daemons will restart when they are given the HUP , or hang-up signal. Apache is one program that operates like this.

The above command will cause Apache to reload its configuration file and resume serving content.

You can list all of the signals that are possible to send with kill by typing:

How To Send Processes Signals by Name

Although the conventional way of sending signals is through the use of PIDs, there are also methods of doing this with regular process names.

The pkill command works in almost exactly the same way as kill , but it operates on a process name instead:

The above command is the equivalent of:

If you would like to send a signal to every instance of a certain process, you can use the killall command:

The above command will send the TERM signal to every instance of firefox running on the computer.

How To Adjust Process Priorities

Often, you will want to adjust which processes are given priority in a server environment.

Some processes might be considered mission critical for your situation, while others may be executed whenever there might be leftover resources.

Linux controls priority through a value called niceness.

High priority tasks are considered less nice, because they don’t share resources as well. Low priority processes, on the other hand, are nice because they insist on only taking minimal resources.

When we ran top at the beginning of the article, there was a column marked “NI”. This is the nice value of the process:

Nice values can range between “-19/-20” (highest priority) and “19/20” (lowest priority) depending on the system.

To run a program with a certain nice value, we can use the nice command:

This only works when beginning a new program.

To alter the nice value of a program that is already executing, we use a tool called renice :

Note: While nice operates with a command name by necessity, renice operates by calling the process PID

Conclusion

Process management is a topic that is sometimes difficult for new users to grasp because the tools used are different from their graphical counterparts.

However, the ideas are familiar and intuitive, and with a little practice, will become natural. Because processes are involved in everything you do with a computer system, learning how to effectively control them is an essential skill.

Источник

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