Process program in linux

Работа с процессами в Linux

Управление процессами является неотъемлемой частью администрирования серверных систем под управлением ОС Linux. В этой практической статье мы рассмотрим примеры решения различных задач по управлению процессами.

Вообще, процесс, как и файл является фундаментальной абстракцией ОС Linux. То есть, без процессов невозможно функционирование данной (как, впрочем, и любой другой) операционной системы.

В рамках данной статьи я не буду сильно погружаться в теорию и рассказывать о том как процессы взаимодействуют с операционной системой и пользователем. На эту тему уже написано достаточно публикаций. Вместо давайте посмотрим, как на практике можно работать с процессами. В качестве тестовой ОС как обычно выступает ОС Linux Ubuntu 22.04.

Получаем список процессов

Каждый процесс имеет свои атрибуты. Это прежде всего идентификатор процесса (PID), также это образ, исполняемый файл, статус выполнения, атрибуты безопасности и т.д.

Получить список процессов с основными атрибутами можно с помощью команды:

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

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

В результате мы получаем дерево процессов, в котором видно какой процесс является родительским для других процессов. Конечно, такую зависимость можно построить и на основании вывода ps сопоставив значение поля PPID (родительский процесс) интересующего процесса с PID соответствующего процесса. Но в виде дерева все выглядит гораздо нагляднее.

Приоритетные и фоновые процессы

Процессы могут быть приоритетными и фоновыми. Приоритетный процесс у нас по сути «прикреплен» к текущему терминалу. То есть он может считывать и передавать данные на стандартные устройства ввода/вывода. Но при этом, наш рабочий терминал будет заблокирован до тех пор, пока запущенный процесс не выполнится. По умолчанию, когда пользователь вводит команду на терминале, создается приоритетный процесс. Это удобно при работе с консольными командами, не требующими значительного времени на выполнение. Но это очень неудобно при использовании различных скриптов, работа которых занимает значительный период времени.

Для таких случаев лучше использовать фоновые процессы. Такие процессы не занимают текущий терминал, то есть мы можем одновременно с выполнением фонового процесса работать с другими командами, запускать процессы и т.д. Фоновый процесс также называется Заданием (Job).

Запустить процесс в фоновом режиме очень просто, достаточно добавить знак & после команды:

После запуска выведется строка с номером задания (в скобках) и PID, появится приглашение на ввод команды в текущем терминале. При этом, номера заданий относятся только к текущему терминалу.

Однако, выполнение этой команды завершится слишком быстро, поэтому для дальнейших примеров я использую скрипт, использующий бесконечный цикл с условием while true…

После запуска в фоновом режиме посмотреть выполнение задание можно с помощью команды jobs:

Приоритетные задачи можно также превращать в фоновые и возвращать обратно в приоритетные.

В качестве примера я снова запущу свой скрипт. Нажатие Ctrl-Z приведет к остановке данного процесса. На рисунке ниже это вывод первой команды jobs. Далее остановленный процесс можно снова запустить в фоновом режиме с помощью команды bg (background). Во втором выводе jobs скрипт запущен со знаком &. И для того, чтобы вернуть процесс в фоновый режим воспользуемся командой fg (foreground).

Читайте также:  Linux remove node js

Вообще, команды fg и bg переводят из/в фоновый режим задание с указанным номером. Но, если номер не указан, действие применяется к последнему созданному заданию, как в нашем случае.

В случае, если нам необходимо завершить процесс, проще всего воспользоваться командой

Однако возможны ситуации, когда процесс может проигнорировать передаваемый ему командой KILL сигнал SIGTERM и не завершить свою работу. В таком случае мы можем воспользоваться командой:

В таком случае передается более мощный сигнал SIGKILL, который нельзя проигнорировать или заблокировать. Как жаль, что такой команды нет в Windows.

Виртуальная файловая система procfs

Виртуальная файловая система procfs, как можно понять из названия расположена только в памяти и не хранится на жестком диске постоянно. Доступ к ней можно получить, обратившись к каталогу /proc.

Как можно увидеть, в этом каталоге содержатся подкаталоги, соответствующие PID процессов. У каждого процесса есть своя запись в /proc с идентификатором в названии. В каждом из этих подкаталогов можно найти ряд файлов, связанных с данным процессом.

Вот основные файлы, которые есть в каждом каталоге процесса:

cmdline — полная командная строка процесса.

В примере для демона SSH видим следующее:

cwd — символьная ссылка на текущий каталог процесса.

exe — символьная ссылка на файл, который должен выполняться.

environ — переменные среды процесса.

fd — содержит ссылку на дескрипторы каждого открытого файла.

Конечно, это не исчерпывающий список тех файлов, которые находятся в каталоге каждого из процессов, так как там можно встретить еще множество файлов, типичных для того, или иного процесса.

Заключение

В этой статье были рассмотрены практические аспекты работы с процессами в ОС Linux. За рамками этой статьи осталась работа с приоритетами и сигналами и многое другое, что будет рассмотрено в следующей статье.

А на бесплатном уроке специализации Linux мои коллеги из OTUS расскажут про базовые команды в Linux. Зарегистрироваться на вебинар можно по этой ссылке.

Источник

How to Manage Linux Processes

Arunachalam B

Arunachalam B

How to Manage Linux Processes

We all follow certain processes to achieve our goals. Similarly, every system has its own processes to accomplish tasks.

Every program or command that executes in a Linux system is called a process.

In this tutorial, let’s explore processes and how we can manage them in Linux.

What is a Linux Process?

A process is theoretically called a program in execution. It’s basically a task that a system is currently working on.

Every action you take on the system will result in a new process. For example, opening a browser initiates a process.

In simple words, a process is an instance of a program. The user action is transformed into a command and a new process will be created upon the execution of the command.

Processes work according to a parent-child hierarchy. As the name of the hierarchy implies, a process initiated from a command/program is called the parent process and the produced process of a parent process is called the child process.

Types of Linux Processes

Processes are classified into 2 types in Linux Distributions:

Foreground processes

A process that requires the user to start it using a Terminal command or Program is called a foreground process. This means that foreground processes require an input trigger from a user. So every foreground process is manually triggered.

Читайте также:  Error loading shared library ld linux x86 64 so 2

Whenever a process is running in the foreground, the other processes should wait until the current process completes.

The best example to demonstrate this is via the sleep command. The sleep command does not allow the user to interact with the terminal until a given number of seconds has passed.

Utfn4bYW2zEfEniaJ4QpFXeMIC9Cru1Ex-2OyRKAk2iGo9b7UBhnEspS3STn7HNOHyfSr081dWR1YgIRYGzkAH5UhfceLH3Xt5RofCs-B71b125bJtKi8vKqRC-IsGWM6N2TVpCapSvkdFclakrqq2LY1zfn4kq2ECAaoL8LAApPoM3ZLKeJahVVCF4qQw

We should wait for 10 seconds to access the terminal to run another command.

Background Processes

A process that runs independently on user input is called a background process. Unlike the foreground processes, we can run multiple processes at the same time in a background process.

To run a process in the background, place an ampersand (&) at the end of the command that you use to start the process.

Here’s a quick example to demonstrate that:

Let’s execute the sleep command in a background process. It’ll run in the background and gives the terminal back to us to run other commands.

99ky8Jj_UgNSPmaxJC1k7KOQdfbN-_hhRh31cfAxpyxECAvJFHJjuHSrRF03epnMcUn14p_-w6I4obtRHBLPmIefL8CWT14hYr4_7WI6H3t6lzOCQWJWtajR_MVFfSiP986loc_qhxToalcOttf99gr6pyGJDgGU80hu3sMkJpJLLNu-VgbKugMiNrqnqQimage-372

Then run the bg command. It takes a process id as an argument and places the process into the background. If the argument is empty it will place the currently suspended process in the background.

image-373

We can see the suspended command ( sudo apt update ) resuming in background.

How to List Linux Processes

Before we go over how to do this, you should know why you might need to know a list of processes. Here are a few reasons:

  1. To know which process consumes more time.
  2. To know which process takes more memory and CPU usage.
  3. To know the triggered command for a running process.

To see the processes that are running currently, we can use ps (Process Status) command:

J0zD8uwiQQbCmoI7kCWQu8MCcoXIfQ9jhpOBnuq3G6xd7qkDxhpRhNGdS7OsLNYuZwllm0eTfsZWNCpr-tlvac38QSduFblom0flRKFg72mmzdN-iEQcv9scx6vu_yjWpRAlIJGays6Y1rfwJpcB3lamtZow6fCIO8gMKTQ8zhcK3XNpA6AKmKcaZcdViA

To list the summary of all processes of every logged-in user, we can use the w command. This command is the combination of the who , uptime and ps -a commands in Linux.

ws5Ip77K3CiODb9gfhjRSP5VQgaegkcabCw_rFcREWfHCnBDYlevoosQagnJ4tNfIG__yAV2OIG_BjzPWdTPx9WF4tMF2PfdTixR0aYu-7oo6vFUASwz-ZiHYxamFJU_nHpKNOlRMsVIthGrVMJtTXATBybJBlHBuTld4F-94PXVOlWJhashtH_f9bkDcg

How to List the Processes in Tree View

When a program/command runs, it initiates a main process called the parent process. The parent process may depend on some other command/program which will create a child process.

Here’s an example screenshot.

Dwa-k101f5l6-Sy3ec8BotbvFggPF4x_UjXdmWpc_YB7AsFb_iKXT-RAjzwA3GhXQI3wa5hdwRBr8hL3eUh4TnyKft_LCPgC0XYDOtLEYeRRBKBGrjZNw3m9irt3XUkaV_7y86LXdRNCssT_Qa1eclk

In the above screenshot, Firefox is the parent process and the other processes are its child processes.

Let’s explore how to list the process in a tree-like structure.

pstree is a Linux command to list the currently running process of all users in a tree-like structure. It is used as a more visual alternative to the ps command.

g1gTo5zkfs92067V3p01xndG6c3XOHPjpHJAZTeT1U4wP1DDLopuxPKlgunnTpFDGZwl5BFIbFuaN5oJoRtiSi9xJcKcQihn_hhNth8R_FKpOdjm-VlQzwO7435ZTmCb2GLXILPO444ZwMxz0ZQVRk4

As we can see, the running processes are in tree form. This can be useful to visualize the processes.

Adding the -p flag with the command will display each branch with its process id.

elX0V2qolKRLEhXmJuPc549_YdTr80Vz5t60XRucXDrYC3_LFKKRDlB_-kP_uJSYvepwX3n6_XQ8jLvzMohI76-gfhSPDO7eD1KEexqRqEfw49K4E2ZpPodobGvnPA0paKsGXHdxDQ1CjVpfTOSduGI

To list the child process(es) of a particular process, pass the process id as an argument to the pstree command.

L_OeZYxLZCDFFxMqelMfvxXWc2g3eKbKlt4EPV1bPfUBGZ5-STfSv9gxSEOksHsWuufeniSgbGS1-w5DL9uzEuQhWRMb7MOXuKpIn3Nr40wBJbDQkOnswClwvLhY0f9o-fuxV_OUwUqY6gDIc6koa0Q

Earlier, I mentioned that pstree command lists the processes from all the users. Passing the username along with the pstree command lists only the processes run by the user.

zTEM4mk9LXPrkBs3KoJ4Y8eBzuH3blStmsX-bgk1ohMwad8LF6hsAXwzSx_aF1vDqE-SdyhhaBWQrNyeuRNN_QHCrU5SY2TFDjnfB1cKbROiBsEBQmLuiXrGPV53ZKJqUGaM6TIYosf3TT1Uk1py-Po

The above screenshot shows the processes running by the root user.

How to See the Processes of a Particular Program

Many developers may have faced the following scenario:

While working on web development projects, we use browsers like Chrome, Firefox, and others to verify the output with different browsers.

Читайте также:  Executing so files linux

Some developers will keep on opening the tabs and never close the opened ones. Due to heavy load (if 150+ tabs are opened) browsers will not respond sometimes 😣 leading to the system hanging up. The worst part could be that we won’t be able to close the browser 😂.

Unlike Windows, we don’t have Task Manager in Linux to kill the browser.

This problem can be solved easily in Linux too. Let’s see how a Linux expert handles this scenario.

We know that every program (including the browser) runs as a process. So then you just have to find the process id and kill it.

Let’s see how to find the process id of a command/program you need.

In my system, Chrome is running, Now we can get the PIDs of Chrome by running the following command:

TUL8R945bAnPXPIZ61Cs6VKzDVLAoRiOGbfZWD-x4u_Jzja72eGqGTXJjC14lhNqa4uF2-jKT3ttOtBJ6f-rbaxqGtEQoI2yPPwanl1ieftWpqMTMFGCn11pfRl2q3s98rehfm0-X7353cJ5KkoM1j2zLxk1CKAM6X-4NMxr_14M0WWdStMC9QhfqbbRrg

How to Kill a Process

There is a command called kill in Linux that is used to kill any process by passing the PID ( Process id ) or Process Name.

Here’s the syntax of the kill command:

KJP27zaj4YOe4BlWlDQskMlX5ymEUfdcATwD-yyD6LpORFMrV7uTC-E8AlvbmQXpTYNKnytLhAmBgORLpCYCRHeTVnjU9lQfIISxcmFpUJtY13rnnPJT5sdYBz3oPkgr9MnXjqx8F8wdU_bAZTM6EhffPLIA9GhD8lrI3o4ysM-QWZdDLptnyEeadAM9HA

The above command will kill the Chrome web browser.

How to List All Processes

We can see all the Linux processes using the top command. It shows real-time updates of each process for all users.

aDFrfxMKy6yydKH81T7o4S-Z5cV552h0qTq34UH_oUuzj-Oml8CQVlzc2rrBUMNCawgMTxxePSFiI0uCTAHWVUMqaxe__JIGJFCbTn8TRoYWqzoDFxeUfmLHH4tphdUr8DYGyLPx-1vfEP-ZaMzfSlLvcNx-qaGTqxSc9JepmJRmbE5Crd6EI52sOt6JRQ

Let’s understand the heading to understand the underlying data.

  • PID represents a Unique process ID.
  • USER represents the Username of the owner of the task.
  • PR represents the Priority of the process. Lower the number, higher the priority.
  • NI represents a Nice Value of task. A Negative nice value implies higher priority, and a positive Nice value means lower priority.
  • VIRT represents the total virtual memory used by the task.
  • RES represents RAM Usage of a process in kilobytes.
  • SHR represents Shared Memory Size ( Kb ) used by a process.
  • S represents the Status of the process:
    D: Uninterruptible sleep
    R: Running
    S: Sleeping
    T: Traced (stopped)
    Z: Zombie
  • CPU represents the CPU usage.
  • MEM represents the memory usage of task.
  • TIME represents the CPU Time.
  • COMMAND represents the command that used to start the process.

To display specific user processes we should use the flag -u :

yDIUnMQBUbjn9xRm0E3pv7yITR_0Kx5bZrxL1L1jrm3dBa_9qidIG_uBpllEZp33BetqHcl6un4lRJR-BI8iXQL7QJE0eI4Q-4BI8vDhXT7arh7m5KPXAlCLMJEQoCCX0uL6RgA5elm3rjkDRVVanBk_djmIGtHbD-Xkf63HVjbtmmhdC39cx8AOANBHyg

You might be confused about seeing the command line output 😆. It’ll be a bit hard to debug the processes in real time.

Here comes the handy GUI tool to handle the processes in Linux. But we have to install this manually. This will work more like task manager in Windows.

_fiYn6xqNuqSEBnqVTkEWhOVPYKoFUxqCkEdE427eWJEsY7WTx1OwuD7p09PG0sZFqrhqdNpYCoM4vhDR7qNB1pe8-uvZVigTUJ0E6BxyU8lgoRzORm4HlihLVsHk1bXgMo0rwHyaGBoajQDb6WQU25NdDRO-U82sYrMg5kxJx7bJrxYKV5yrdlAN2xMcQ

When we right-click on any process it will show the actions like kill, stop, end, and so on.

The Resources tab shows the following utilities:

  1. CPU History
  2. Memory and Swap History
  3. Network History

0IB18GszrBCvE8827Ml5XuxtXlMZFVbgs5PcZkEN99BIeVjO2BOaULR55yjlbLrYA-i9qURCF4JC8mpxOkZ4_HZLGTDjRUnW5jHdfKzoEBToSYvm95bs5FnQvHYgGYbhPalFXq8D2DONHZGlWM-g1XACnt_FxpN4q7Wr8DUogBsPeuMXXMluIw01z9YbFAxSO96ReEMCKtAgc11bigR6jwThKyjlk0Fz8oZt6hXh5ld4Rt9WWIEtZ-TOrZJ0tQFfx-lnCnH3vJjTBjzfFEulCzcAJgJqeDh8XrK3Ul9iH9Yant3FAbtmWMx5A9FyGcvHydw2nL-JBTGoWcaxUUkoTAiFMgiIuDQW4PVuMYjswFJPERQManNjiADfQ61AVo_9BWdfg0i_mtnCOUennGxyXwqPP_EgaiGwK8Wli7SHAGXQdtbUzu4BElWCvNkpxLLan7y3NGnlaCICiMwnRJ513_gOntCbPwT9w87husha2v6TeDPw-ey0-F_t3wnq7qlN3q9IpScjaR5BDFHRiWd1ywaSSeV_xEl1FC0cotqXcytTl0vYwciJrQc6fQ

These graphs will be useful to determine the load in your system.

Conclusion

In this article, you have learned the basics of processes in Linux. I hope you now understand how they work a bit better. I recommend you all try these commands in your system.

To learn more about Linux, subscribe to my email newsletter at my site and follow me on social media.

Источник

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