- How to check running process in Ubuntu Linux using command line
- Check running process in Ubuntu Linux
- How to manage processes from the Ubuntu Linux terminal
- Ubuntu Linux pgrep command
- Ubuntu Linux top and htop commands
- Ubuntu Linux kill command
- Ubuntu Linux pkill command
- Ubuntu Linux killall command
- Ubuntu Linux nice and renice command
- Conclusion
- Изучаем процессы в Linux
- Содержание
- Введение
- Атрибуты процесса
- Жизненный цикл процесса
- Рождение процесса
- Состояние «готов»
- Состояние «выполняется»
- Перерождение в другую программу
- Состояние «ожидает»
- Состояние «остановлен»
- Завершение процесса
- Состояние «зомби»
- Забытье
- Благодарности
- Bash check if process is running or not on Linux / Unix
- Bash check if process is running or not
- What is a Linux or Unix process?
- Is nginx process is running or not?
- Bash check process running with pidof command
- Bash shell check if a process is running or not with ps
- Determine whether a process is running or not using a shell script
- Linux/Unix bash command to determine if process is running
- Bash shell script to check running process
- A note about service and systemctl command
- Conclusion
How to check running process in Ubuntu Linux using command line
I am a new Ubuntu sysadmin for the Ubuntu Linux operating system. How do I check running process in Ubuntu Linux using the command line option?
One can use the Ubuntu Linux command line or terminal app to display a running process, change their priorities level, delete process and more. This page shows how to use various commands to list, kill and manage process on Ubuntu Linux.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Ubuntu Linux |
Est. reading time | 5m |
Check running process in Ubuntu Linux
The procedure to monitor the running process in Ubuntu Linux using the command line is as follows:
- Open the terminal window on Ubuntu Linux
- For remote Ubuntu Linux server use the ssh command for log in purpose
- Type the ps aux command to see all running process in Ubuntu Linux
- Alternatively, you can issue the top command/htop command to view running process in Ubuntu Linux
Let us see some example and usage for Ubuntu Linux in details.
NOTE: Please note that >$
- 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 ➔
How to manage processes from the Ubuntu Linux terminal
The ps command is a traditional Ubuntu Linux command to lists running processes. The following command shows all processes running on your system: There may be too many processes. Hence, it uses the following less command/more command as pipe to display process one screen at a time: >$ sudo ps -aux | less >$ sudo ps aux | grep chromium-browser >$ sudo ps -aux | egrep ‘sshd|openvpn’ Many variants of Ubuntu Linux comes with the pgrep command to search/find process. The syntax is: The top command is another highly recommended method to see your Ubuntu Linux servers resource usage. One can see a list of top process that using the most memory or CPU or disk. Want to kill a process? Try kill command. The syntax is: >$ kill -signal pid >$ kill 3932 If you wish to kill a process by name, try pkill command. The syntax is: >$ sudo pkill -KILL php7-fpm The killall command kills processes by name, as opposed to the selection by PID as done by kill command: >$ killall -9 emacs The primary purpose of the nice command is to run a process/command at a lower or higher priority. Use the renice command to alter the nice value of one or more running Ubuntu Linux processes. The nice value can range from -20 to 19, with 19 being the lowest priority. Say, you want to compile software on a busy Ubuntu Linux server. You can set a very low priority, enter: >$ nice -n 13 cc -c *.c & To change the priority of a running process, type the following: >$ sudo renice -10 $(pgrep vim) This page shows how to manage the process on the Ubuntu Linux terminal. For further info see man pages or our example pages: 🐧 Get the latest tutorials on Linux, Open Source & DevOps via Источник Данная статья в большей мере рассчитана на новичков в системном программировании и тех, кто просто хочет узнать немного больше о том, как работают процессы в Linux. Всё написанное ниже справедливо к Debian Linux с ядром 4.15.0. Системное программное обеспечение взаимодействует с ядром системы посредством специальных функций — системных вызовов. В редких случаях существует альтернативный API, например, procfs или sysfs, выполненные в виде виртуальных файловых систем. Процесс в ядре представляется просто как структура с множеством полей (определение структуры можно прочитать здесь). Только один процесс в системе рождается особенным способом — init — он порождается непосредственно ядром. Все остальные процессы появляются путём дублирования текущего процесса с помощью системного вызова fork(2) . После выполнения fork(2) получаем два практически идентичных процесса за исключением следующих пунктов: После выполнения fork(2) все ресурсы дочернего процесса — это копия ресурсов родителя. Копировать процесс со всеми выделенными страницами памяти — дело дорогое, поэтому в ядре Linux используется технология Copy-On-Write. Сразу после выполнения fork(2) переходит в состояние «готов». Как только планировщик поставил процесс на выполнение, началось состояние «выполняется». Процесс может выполняться весь предложенный промежуток (квант) времени, а может уступить место другим процессам, воспользовавшись системным вывозом sched_yield . В некоторых программах реализована логика, в которой родительский процесс создает дочерний для решения какой-либо задачи. Ребёнок в данном случае решает какую-то конкретную проблему, а родитель лишь делегирует своим детям задачи. Например, веб-сервер при входящем подключении создаёт ребёнка и передаёт обработку подключения ему. или библиотечным вызовам execl(3), execlp(3), execle(3), execv(3), execvp(3), execvpe(3) : Все из перечисленных вызовов выполняют программу, путь до которой указан в первом аргументе. В случае успеха управление передаётся загруженной программе и в исходную уже не возвращается. При этом у загруженной программы остаются все поля структуры процесса, кроме файловых дескрипторов, помеченных как O_CLOEXEC , они закроются. Как не путаться во всех этих вызовах и выбирать нужный? Достаточно постичь логику именования: Семейство вызовов exec* позволяет запускать скрипты с правами на исполнение и начинающиеся с последовательности шебанг (#!). Есть соглашение, которое подразумевает, что argv[0] совпадает с нулевым аргументов для функций семейства exec*. Однако, это можно нарушить. Любопытный читатель может заметить, что в сигнатуре функции int main(int argc, char* argv[]) есть число — количество аргументов, но в семействе функций exec* ничего такого не передаётся. Почему? Потому что при запуске программы управление передаётся не сразу в main. Перед этим выполняются некоторые действия, определённые glibc, в том числе подсчёт argc. Некоторые системные вызовы могут выполняться долго, например, ввод-вывод. В таких случаях процесс переходит в состояние «ожидает». Как только системный вызов будет выполнен, ядро переведёт процесс в состояние «готов». В любой момент можно приостановить выполнение процесса, отправив ему сигнал SIGSTOP. Процесс перейдёт в состояние «остановлен» и будет находиться там до тех пор, пока ему не придёт сигнал продолжать работу (SIGCONT) или умереть (SIGKILL). Остальные сигналы будут поставлены в очередь. Ни одна программа не умеет завершаться сама. Они могут лишь попросить систему об этом с помощью системного вызова _exit или быть завершенными системой из-за ошибки. Даже когда возвращаешь число из main() , всё равно неявно вызывается _exit . Сразу после того, как процесс завершился (неважно, корректно или нет), ядро записывает информацию о том, как завершился процесс и переводит его в состояние «зомби». Иными словами, зомби — это завершившийся процесс, но память о нём всё ещё хранится в ядре. Код возврата и причина завершения процесса всё ещё хранится в ядре и её нужно оттуда забрать. Для этого можно воспользоваться соответствующими системными вызовами: Вся информация о завершении процесса влезает в тип данных int. Для получения кода возврата и причины завершения программы используются макросы, описанные в man-странице waitpid(2) . Передача argv[0] как NULL приводит к падению. Бывают случаи, при которых родитель завершается раньше, чем ребёнок. В таких случаях родителем ребёнка станет init и он применит вызов wait(2) , когда придёт время. После того, как родитель забрал информацию о смерти ребёнка, ядро стирает всю информацию о ребёнке, чтобы на его место вскоре пришёл другой процесс. Спасибо Саше «Al» за редактуру и помощь в оформлении; Спасибо Саше «Reisse» за понятные ответы на сложные вопросы. Они стойко перенесли напавшее на меня вдохновение и напавший на них шквал моих вопросов. Источник Bash commands to check running process: Let us see some examples about checking processes that running or not in Linux and Unix systems. Join Patreon ➔ A Linux process is nothing but an executing (i.e., running) instance of a program. For example, Apache or Nginx web server runs on Linux or Unix-like system to display web pages in the background. All running process in the background is called as Daemon. So Apache/Nginx is a class of processes that run continuously in the background, and we say nginx or httpd daemon is running on the server. However, how do you verify that Nginx or HTTPD is running? You need to use the commands. The syntax is: Again the syntax is: Each Linux or Unix bash shell command returns a status when it terminates normally or abnormally. You can use command exit status in the shell script to display an error message or take some sort of action. You can use special shell variable called $? to get the exit status of the previously executed command. To print ? variable use the echo command: A 0 exit status means the command was successful without any errors. A non-zero (1-255 values) exit status means command was failure. It is now easy to check if the process was found or not using exit status value: Click to enlarge Bash if..else..fi statement allows to make choice based on the success or failure of a command: One can use systemctl command to control the systemd system under Linux. It can provide status of service too. For example, find out if nginx is running or out, run: You learned how to determine whether a process is running or not and use a conditional shell script to start/stop process based on that condition. See pgrep and bash man page here for more information. 🐧 Get the latest tutorials on Linux, Open Source & DevOps via Comments on this entry are closed. Thank you for this article, it helped me a lot to check if a program that I run in rc.local (Raspberrry) was working or not and to check for how long it is running. I have a trouble with the continuity of this program running. It starts automatically with the raspberry start on, but frequently the program stop working and close (never run more than two days). I was thinking about to handling this error rebboting the system programatically every hour for example. Could you help me to find out where to looking for a solution or if it is possible to check by a routine(code) if the program is running or not as a condition to reboot or not the system? Источник
Press q to exit from above Ubuntu Linux pagers. You can search for a particular Ubuntu Linux process using grep command/egrep command: Ubuntu Linux pgrep command
Ubuntu Linux top and htop commands
Ubuntu Linux kill command
Find PID using ps, pgrep or top command. Say you want to kill a PID # 3932, run:
For some reason if the process can not be killed, try forceful killing: Ubuntu Linux pkill command
Ubuntu Linux killall command
Ubuntu Linux nice and renice command
Set a very high priority for a kernel update. Before rebooting Ubuntu Linux server, run:Conclusion
Изучаем процессы в Linux
В этой статье я хотел бы рассказать о том, какой жизненный путь проходят процессы в семействе ОС Linux. В теории и на примерах я рассмотрю как процессы рождаются и умирают, немного расскажу о механике системных вызовов и сигналов.Содержание
Введение
Атрибуты процесса
Но так как статья посвящена системному программированию, а не разработке ядра, то несколько абстрагируемся и просто акцентируем внимание на важных для нас полях процесса:
Жизненный цикл процесса
Рождение процесса
Все страницы памяти родителя помечаются как read-only и становятся доступны и родителю, и ребёнку. Как только один из процессов изменяет данные на определённой странице, эта страница не изменяется, а копируется и изменяется уже копия. Оригинал при этом «отвязывается» от данного процесса. Как только read-only оригинал остаётся «привязанным» к одному процессу, странице вновь назначается статус read-write.Состояние «готов»
Фактически, процесс стоит в очереди и ждёт, когда планировщик (scheduler) в ядре даст процессу выполняться на процессоре.Состояние «выполняется»
Перерождение в другую программу
Однако, если нужно запустить другую программу, то необходимо прибегнуть к системному вызову execve(2) :
Состояние «ожидает»
В Linux так же существует состояние «ожидает», в котором процесс не реагирует на сигналы прерывания. В этом состоянии процесс становится «неубиваемым», а все пришедшие сигналы встают в очередь до тех пор, пока процесс не выйдет из этого состояния.
Ядро само выбирает, в какое из состояний перевести процесс. Чаще всего в состояние «ожидает (без прерываний)» попадают процессы, которые запрашивают ввод-вывод. Особенно заметно это при использовании удалённого диска (NFS) с не очень быстрым интернетом.Состояние «остановлен»
Завершение процесса
Хотя аргумент системного вызова принимает значение типа int, в качестве кода возврата берется лишь младший байт числа.Состояние «зомби»
Более того, это второе состояние, в котором процесс может смело игнорировать сигнал SIGKILL, ведь что мертво не может умереть ещё раз.Забытье
Благодарности
Bash check if process is running or not on Linux / Unix
Bash check if process is running or not
What is a Linux or Unix process?
Is nginx process is running or not?
Bash check process running with pidof command
pidof program
pidof httpd
pidof mysqld
pidof nginxBash shell check if a process is running or not with ps
ps -C daemon
ps -C nginx
ps -C httpd
It is common to use the grep command or egrep command with ps as follows:
ps aux | grep nginx
ps aux | egrep -i «(nginx|httpd)»Determine whether a process is running or not using a shell script
pgrep -x mysqld
echo $?
pgrep -x nginx
echo $?
pidof httpd
echo $?
ps -C httpd
echo $? Linux/Unix bash command to determine if process is running
Bash shell script to check running process
A note about service and systemctl command
systemctl status
systemctl status sshd
systemctl status nginx
Older Linux distros and Unix like system such as FreeBSD use service command for the same purpose. The syntax is:
sudo service
sudo service nginx status
sudo service sshd status Conclusion
Category List of Unix and Linux commands Documentation help • mandb • man • pinfo Disk space analyzers df • duf • ncdu • pydf File Management cat • cp • less • mkdir • more • tree Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 Linux Desktop Apps Skype • Spotify • VLC 3 Modern utilities bat • exa Network Utilities NetHogs • dig • host • ip • nmap OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 Package Manager apk • apt Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop Searching ag • grep • whereis • which Shell builtins compgen • echo • printf Text processing cut • rev User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04