Long running process in linux

Содержание
  1. Linux , 3 ways to keep long running processes in background
  2. Как узнать, как долго длится процесс в Linux
  3. Узнать, как долго длится процесс в Linux
  4. You may also like
  5. 📜 Чтение файла построчно на Bash
  6. 📧 В чем разница между IMAP и POP3
  7. ✔️ Как управлять контейнерами LXD от имени обычного.
  8. 📜 Руководство для начинающих по созданию первого пакета.
  9. Феноменальная популярность электроники Xiaomi: основные причины
  10. 📜 Получение вчерашней даты в Bash: Практическое руководство
  11. Использование специальных гелей при мышечных болях
  12. 📦 Как расширить/увеличить файловую систему VxFS на Linux
  13. Услуги по размещению серверного оборудования в ЦОД
  14. Для чего выполняется ИТ консалтинг на предприятиях?
  15. Leave a Comment Cancel Reply
  16. • Свежие записи
  17. • Категории
  18. • Теги
  19. • itsecforu.ru
  20. • Страны посетителей
  21. IT is good
  22. Maintaining a long-running task on Linux
  23. 4 Answers 4
  24. How to Check Long Running Processes in Linux
  25. How to Check Long Running Processes in Linux
  26. 1. Shell Script to Check How Long High CPU Consumption Processes Run in Linux
  27. 2. Shell Script to Check Top Memory Consuming Processes
  28. How to check how long a process has been running?

Linux , 3 ways to keep long running processes in background

In Linux, there are several ways to keep a long running process running in the background. Here are a few common methods:

You can run a command in the background by appending an ampersand (&) to the end of the command. For example, to run a process called myprogram in the background, you can use the following command:

This will start the process and immediately return control to the terminal, allowing you to continue using the command line.

If you want to ensure that the process continues running even if you log out of the terminal or close the terminal window, you can use the nohup command. For example, to run a process called myprogram with nohup, you can use the following command:

This will start the process in the background and redirect its output to a file called nohup.out in the current directory. You can safely log out of the terminal or close the terminal window without stopping the process.

If you want to start a long running process that requires user interaction (such as a text editor), and you want to detach the process from the terminal so you can log out and log back in later, you can use the screen command. Here’s how:

  • Run the long running process in the new screen session.
  • Detach the screen session by pressing Ctrl+a followed by d.
  • Log out of the terminal or close the terminal window.
  • Log back in to the terminal and reattach the screen session:

This will bring you back to the screen session where you started the long running process.

Источник

Как узнать, как долго длится процесс в Linux

Вы когда-нибудь хотели узнать, как долго процесс запускается в вашем Linux-боксе?

Это краткое руководство поможет вам узнать время работы активного процесса.

Вам не нужны никакие приложения для мониторинга.

В Unix-подобных операционных системах существует команда ps, которая используется для отображения информации об активных процессах.

Используя команду ps, мы можем легко узнать, как долго работает процесс.

Узнать, как долго длится процесс в Linux

Команда ps имеет разные спецификаторы формата (ключевые слова), которые могут использоваться для управления выходным форматом.

Читайте также:  Linux создание локальной сети

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

  • etime – прошедшее время с момента запуска процесса в виде [[DD-] hh:] mm: ss.
  • etimes – прошедшее время с момента запуска процесса в секундах.

Во-первых, вам нужно узнать PID процесса. Следующая команда отображает PID процесса dhcpcd.

Как видно из вышеприведенного вывода, 8299 является PID процесса dhcpcd.

Теперь мы можем узнать, как долго этот процесс выполнялся с помощью команды:

$ ps -p 8299 -o etime ELAPSED 04:05:37

Вы также можете просмотреть прошедшее время в секундах, используя ключевое слово etimes.

$ ps -p 8299 -o etimes ELAPSED 14749

Find out how long a process has been running in Linux

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

ps -eo pid,comm,lstart,etime,time,args
ps -eo pid,comm,lstart,etimes,time,args

Первая команда отображает время безотказной работы всех процессов Linux в формате [[DD-] hh:] mm: ss, а на последнем отображает время безотказной работы в секундах.

Вот пример вывода второй команды.

uptime of all processes in Linux

Как видно из вышесказанного, у нас есть время безотказной работы всех процессов с шестью столбцами.

  • PID – идентификатор процесса
  • COMMAND (второй столбец) – имя команды без параметров и / или аргументов.
  • STARTED – абсолютное время начала процесса.
  • ELAPSED – Истекшее время с момента запуска процесса в виде [[dd-] hh:] mm: ss.
  • TIME – суммарное время процессора, “[dd-] hh: mm: ss” format.
  • COMMAND (последний столбец) – имя команды со всеми ее опциями и аргументами.

Для получения дополнительной информации о команде ps проверьте страницы руководства.

И это все на данный момент. Теперь вы знаете, как узнать, как долго работает процесс в вашей Linux-системе. Надеюсь это поможет. Я скоро буду здесь с другим полезным руководством.

itisgood
4 способа сохранить выполнение команды после выхода из сеанса SSH
Как запускать команду Linux каждые X секунд навсегда

You may also like

📜 Чтение файла построчно на Bash

📧 В чем разница между IMAP и POP3

✔️ Как управлять контейнерами LXD от имени обычного.

📜 Руководство для начинающих по созданию первого пакета.

Феноменальная популярность электроники Xiaomi: основные причины

📜 Получение вчерашней даты в Bash: Практическое руководство

Использование специальных гелей при мышечных болях

📦 Как расширить/увеличить файловую систему VxFS на Linux

Услуги по размещению серверного оборудования в ЦОД

Для чего выполняется ИТ консалтинг на предприятиях?

Leave a Comment Cancel Reply

• Свежие записи

• Категории

• Теги

• itsecforu.ru

• Страны посетителей

IT is good

В этой статье вы узнаете, как удалить удаленный Git-репозиторий. Процесс прост, но его полезно запомнить, чтобы избежать неожиданностей в будущем. Git – это…

В 11-й версии своей операционной системы Microsoft серьезно переработала интерфейс и убрала несколько привычных функций. Нововведения не всем пришлись по душе. Мы дадим…

Продажа ноутбука нередко становится хлопотным занятием. Кроме поиска покупателя, продавцу необходимо подготовить устройство перед проведением сделки. Но если последовательно выполнить все шаги, ничего…

Вы можете оказаться в ситуации, когда вам нужно использовать скрипт шелла для чтения файлов построчно. В этом руководстве я расскажу о нескольких способах…

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

Источник

Maintaining a long-running task on Linux

My system includes a task which opens a network socket, receives pushed data from the network, processes it, and writes it out to disk or pings other machines depending on the messages. This task is intended to run forever, and the service is designed to have this task always running. But sometimes it crashes. What’s the best practice for keeping a task like this alive? Assume it’s okay for the task to be dead for up to 30 seconds before we restart it. Some obvious ideas include having a watchdog process that checks to make sure the process is still running. Watchdog could be triggered by cron . But how does it know if the process is alive or not? Write a pidfile? touch a heartbeat file? An ideal solution wouldn’t continuously spin up more processes if the machine gets bogged down to the point where the watchdog is running faster than the heartbeat. Are there standard linux tools for this? I can imagine a solution that uses a message queue, but I’m not sure if that’s a good idea or not.

Читайте также:  What is linux mint recovery mode

4 Answers 4

Depending on the nature of the task that you wish to monitor, one method is to write a simple wrapper to start up your task in a fork().

The wrapper task can then do a waitpid() on the child and restart it if it is terminated.

This does depend on modifying the source for the task that you wish to run.

sysvinit will restart processes that die, if added to inittab .

If you’re worried about the process freezing without crashing and ending the process, you can use a heartbeat and hard kill the active instance, letting init restart it.

Источник

How to Check Long Running Processes in Linux

check long running processes in linux

It is important to keep track of long running processes on your system, whether you are a system administrator or not. Long running processes take up a lot of CPU processing and memory, and can slow down your system. Sometimes they may even stop working and slow down your system. In this article, we will check long running processes in Linux. Once you have determined the long running processes on your system, you can kill them if they have become non-responsive. You can use these steps on almost every Linux system.

How to Check Long Running Processes in Linux

We will mainly use ps command to identify long running processes in Linux. It stands for process status and displays the information about active/running processes. It provides useful details such as username, PID, cpu usage, memory usage, process start date & time, etc.

1. Shell Script to Check How Long High CPU Consumption Processes Run in Linux

Here is the command to find out list of users running processes and save the output to /tmp/long-running-processes.txt file.

ps -eo pid,user,ppid,%mem,%cpu,cmd --sort=-%cpu | head | tail -n +2 | awk '' > /tmp/long-running-processes.txt

You can use this information to get process run time by user and commands.

Create an empty shell script.

$ sudo vi long-process-cpu-usage.sh

Add the following lines to it.

#!/bin/bash ps -eo pid,user,ppid,%mem,%cpu,cmd --sort=-%cpu | head | tail -n +2 | awk '' > /tmp/long-running-processes.txt echo "--------------------------------------------------" echo "UName PID CMD Process_Running_Time" echo "--------------------------------------------------" for userid in `cat /tmp/long-running-processes.txt` do username=$(ps -u -p $userid | tail -1 | awk '') pruntime=$(ps -p $userid -o etime | tail -1) ocmd=$(ps -p $userid | tail -1 | awk '') echo "$username $userid $ocmd $pruntime" done | column -t echo "--------------------------------------------------"

Save and close the file. Make it an executable with the following command.

$ sudo chmod +x long-process-cpu-usage.sh

When you run the above script, you will see the following output.

# sh /opt/scripts/long-running-cpu-proc.sh ---------------------------------------------------- UName PID CMD Process_Running_Time ---------------------------------------------------- Ubuntu 3214 Web 01:18:48 Ubuntu 3748 Web 01:08:20 Ubuntu 1639 firefox 01:44:51 Ubuntu 3793 nautilus 24:14 Ubuntu 3301 Web 57:40 ----------------------------------------------------

2. Shell Script to Check Top Memory Consuming Processes

Here is a shell script you can use to get top memory consuming processes on your system.

$ sudo vi long-running-memory-process.sh

Add the following lines to it.

#!/bin/bash ps -eo pid,user,ppid,%mem,%cpu,cmd --sort=-%mem | head | tail -n +2 | awk '' > /tmp/long-running-processes-1.txt echo "--------------------------------------------------" echo "UName PID CMD Process_Running_Time" echo "--------------------------------------------------" for userid in `cat /tmp/long-running-processes-1.txt` do username=$(ps -u -p $userid | tail -1 | awk '') pruntime=$(ps -p $userid -o etime | tail -1) ocmd=$(ps -p $userid | tail -1 | awk '') echo "$username $userid $ocmd $pruntime" done | column -t echo "--------------------------------------------------"

Save and close the file. Make the file executable.

$ chmod +x long-running-memory-process.sh

When you run the script you will see the following output.

# sh /opt/scripts/long-running-memory-process.sh ---------------------------------------------------- UName PID CMD Process_Running_Time ---------------------------------------------------- ubuntu 3639 firefox 08:44:56 ubuntu 3997 Web 07:39:54 ubuntu 3269 Web 09:18:37 ubuntu 2712 Web 10:44:55 ----------------------------------------------------

In this article, we have looked at two shell scripts to get memory consumption of long running processes.

Читайте также:  Адрес текущей директории linux

Источник

How to check how long a process has been running?

On Linux with the ps from procps(-ng) (and most other systems since this is specified by POSIX):

Where $$ is the PID of the process you want to check. This will return the elapsed time in the format [[dd-]hh:]mm:ss .

Using -o etime tells ps that you just want the elapsed time field, and the = at the end of that suppresses the header (without, you get a line which says ELAPSED and then the time on the next line; with, you get just one line with the time).

Or, with newer versions of the procps-ng tool suite (3.3.0 or above) on Linux or on FreeBSD 9.0 or above (and possibly others), use:

(with an added s ) to get time formatted just as seconds, which is more useful in scripts.

On Linux, the ps program gets this from /proc/$$/stat , where one of the fields (see man proc ) is process start time. This is, unfortunately, specified to be the time in jiffies (an arbitrary time counter used in the Linux kernel) since the system boot. So you have to determine the time at which the system booted (from /proc/stat ), the number of jiffies per second on this system, and then do the math to get the elapsed time in a useful format.

It turns out to be ridiculously complicated to find the value of HZ (that is, jiffies per second). From comments in sysinfo.c in the procps package, one can A) include the kernel header file and recompile if a different kernel is used, B) use the posix sysconf() function, which, sadly, uses a hard-coded value compiled into the C library, or C) ask the kernel, but there’s no official interface to doing that. So, the ps code includes a series of kludges by which it determines the correct value. Wow.

So it’s convenient that ps does that all for you. 🙂

Источник

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