Linux посмотреть процессы php

Как получить список запущенных php-скриптов, использующих PHP exec ()?

Мне нужно знать и убивать, если есть какие-то процессы, выполняющие указанный PHP script. Возможно ли получить список процессов, выполняющих sample.php с помощью exec() и PHP скрипт.

4 ответа

exec("ps auxwww|grep sample.php|grep -v grep", $output); 

Это будет работать, однако, если PHP работает в режиме CGI. Если он работает как тип SAPI, вы никогда не увидите «sample.php» в списке процессов, просто «httpd».

Спасибо, это работает, но какие цифры показаны здесь? 1025 19622 0.0 0.0 5336 1308 ? S 02:15 0:00 wget -q http://www.example.com/sample.php

идентификатор родительского процесса, идентификатор процесса, использование процессора, использование памяти и т. д. Подробнее смотрите в man ps .

Нет. Поскольку PHP запускается через apache/nginx. В случае доступа к командной строке proccess называется PHP, а не фактическим именем вашего script.

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

загрузить yikes.php. идентифицируйте идентификатор процесса (это должно быть первое целое число, в которое вы попадаете в каждом индексе массива). скопируйте и вставьте его в url как? pid = XXXXX. и он ушел.

//http://website.com/yikes.php?pid=668 $pid = $_GET['pid']; exec("ps auxwww|grep name-of-file.php|grep -v grep", $output); echo '
'; print_r($output); echo '

'; // exec("kill $pid");

Это зависит от множества факторов, включая ОС, версию PHP и т.д., но вы можете попробовать использовать сигналы, чтобы получить script, чтобы дать вам свое имя, а затем прекратить, если оно соответствует. Или, script зарегистрировать свой pid, а затем сравнить с запущенными процессами.

Ещё вопросы

  • 0 Извлечь значения между символами в MySQL?
  • 1 Выполнить ручной откат в среде JTA в EJB без сохранения состояния
  • 0 Не получить данные JSON в PHP
  • 0 JQuery удалить класс и добавить в другой div не работает
  • 0 ng Cordova file_uri к base64
  • 0 Временно отсоединить перетаскиваемое колесо мыши от карты масштабирования / панорамирования?
  • 1 Использование конкретных номеров для достижения целевого числа
  • 1 Классы Java от WSDL и Eclipse
  • 1 Распечатать список в указанном диапазоне Python
  • 0 Метод SVD в с ++
  • 0 Angularjs отображать HTML в специальных символах
  • 0 Вывести кортеж в списке STL
  • 1 Укажите имя БД / схемы Oracle в tomcat context.xml
  • 1 SQLDataReader с пустым чтением после ExecuteReader
  • 0 Как вписать исходный текстовый формат абзаца в элемент HTML-абзаца с помощью jquery?
  • 1 Часто неправильно используется: аутентификация — фортификация
  • 0 Добавить дополнительные btn-group onclick
  • 0 Как мне найти префикс в таблице MySQL?
  • 0 php: невозможно выполнить итерацию для каждого цикла
  • 0 почему мой мод начальной загрузки не открывается?
  • 0 Способы передачи информации из PHP в JQUERY?
  • 1 я могу заменить regExp другим regExp?
  • 0 Перебирать вложенные объекты — если поле соответствует переменной, обновите $ scope
  • 1 Цветовой список состояний «событие» не вызван или не обработан
  • 1 unregisterReceiver (получатель) в onPause заставляет получателя не регистрироваться
  • 1 Не удается импортировать установленный пакет в среде Python3 ноутбука Jupyter
  • 1 AssertAlmostEqual для значения в dict
  • 1 Как вызвать исходную функцию JavaScript, которая сначала была переопределена расширением?
  • 0 MySQL SELECT, если нет более новой записи
  • 1 Apk не устанавливается на Oreo
  • 0 Отладка сортировки слиянием
  • 0 Создать простой список задач J Query
  • 0 Воспроизведение видео HTML5 внутри рамки изображения iPhone
  • 0 Drupal 7 Изображение Модуль PHP Вывод
  • 1 Отладка исходного кода сгенерированного кода в IntelliJ
  • 1 Vue.js + Require.js расширяющий родительский
  • 1 Невозможно запустить приложение на Android 7.1.2 через appium в Eclipse
  • 0 Как добавить ng-шаблон в mvc @ Html.TextBoxFor (…)?
  • 1 Кэширование в памяти с ограничением по времени в python
  • 1 Не удается получить информацию XML в Java
  • 1 Создать строку из n символов без цикла [duplicate]
  • 0 Попытка сделать простую вещь в AngularJS: form->, если вы поставите правильное слово-> появляется кнопка-> вы можете нажать и перейти на другую страницу;
  • 0 настроить веб-страницу под любое устройство
  • 1 NAudio Asio Запись и воспроизведение
  • 1 прокси nginx для клиента Javascript WebSocket
  • 0 JQuery: получение данных не работает
  • 0 Angular — фиксировать заголовок, пока анимируется представление ngAnimate.
  • 0 Mysql конвертировать целое число в дату
  • 0 Mysql Ошибка подключения к базе данных

Источник

getmypid

Returns the current PHP process ID, or false on error.

Notes

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

See Also

  • getmygid() — Get PHP script owner’s GID
  • getmyuid() — Gets PHP script owner’s UID
  • get_current_user() — Gets the name of the owner of the current PHP script
  • getmyinode() — Gets the inode of the current script
  • getlastmod() — Gets time of last page modification

User Contributed Notes 14 notes

The lock-file mechanism in Kevin Trass’s note is incorrect because it is subject to race conditions.

For locks you need an atomic way of verifying if a lock file exists and creating it if it doesn’t exist. Between file_exists and file_put_contents, another process could be faster than us to write the lock.

The only filesystem operation that matches the above requirements that I know of is symlink().

Thus, if you need a lock-file mechanism, here’s the code. This won’t work on a system without /proc (so there go Windows, BSD, OS X, and possibly others), but it can be adapted to work around that deficiency (say, by linking to your pid file like in my script, then operating through the symlink like in Kevin’s solution).

define ( ‘LOCK_FILE’ , «/var/run/» . basename ( $argv [ 0 ], «.php» ) . «.lock» );

if (! tryLock ())
die( «Already running.\n» );

# remove the lock on exit (Control+C doesn’t count as ‘exit’?)
register_shutdown_function ( ‘unlink’ , LOCK_FILE );

# The rest of your script goes here.
echo «Hello world!\n» ;
sleep ( 30 );

function tryLock ()
# If lock file exists, check if stale. If exists and is not stale, return TRUE
# Else, create lock file and return FALSE.

if (@ symlink ( «/proc/» . getmypid (), LOCK_FILE ) !== FALSE ) # the @ in front of ‘symlink’ is to suppress the NOTICE you get if the LOCK_FILE exists
return true ;

# link already exists
# check if it’s stale
if ( is_link ( LOCK_FILE ) && ! is_dir ( LOCK_FILE ))
unlink ( LOCK_FILE );
# try to lock again
return tryLock ();
>

Источник

Find what PHP script is running on each HTTPD process

I’d like to know a way of inspecting HTTPD processes to find which PHP script is running on them. I already did a «netstat» and found that some processes held DB and Network sockets for too long and now i want to know what scripts are causing it. Btw, i’m using Linux.

2 Answers 2

You need to have Apache module mod_status enabled (CentOs main Apache config file is located at /etc/httpd/conf/httpd.conf)

LoadModule status_module modules/mod_status.so 

with option ExtendedStatus on (this is to be set in the same config file as above)

# ExtendedStatus controls whether Apache will generate "full" status # information (ExtendedStatus On) or just basic information (ExtendedStatus # Off) when the "server-status" handler is called. The default is Off. # ExtendedStatus On 

and some access rights set for that (replace below XXX.XXX.XXX.XXX with your IP — this is to be found in the same config file as above)

# Allow server status reports generated by mod_status, # with the URL of http://servername/server-status # Change the ".example.com" to match your domain to enable. # SetHandler server-status Order deny,allow Deny from all Allow from localhost 127.0.0.1 XXX.XXX.XXX.XXX 

Finally you will be seing what each HTTPD process is doing by accessing http://your-server-name/server-status

This will show the pids and URLs currently being processed in the way presented here.

Someone upvoted this today, so I came back to have a look at what I wrote. Reviewing the question and my answer. yes I answered the question but solving the problem would be better served by logging %D and analyzing the data.

The suggested mod_status is a great alternative to see what process is doing what at the moment, you enable it (and usually add Allow statements to permit you to view it from the IP range you access the webserver from) and then browse to http://site.name/server-status and get nice output. An example can be seen at Apaches own site: http://www.apache.org/server-status

Another useful tool to see whats going on with a process is lsof , if you have a known PID that «hangs» you can type lsof -p to see whats going on with that one. To match all processes you can type something like lsof -c apache or lsof -c httpd . Its a very versatile tool with lots of options for what you want to see.

Finally you have strace that can attach to running processes to see what they are doing at the moment with system calls, etc. strace -p for example. Warning, this CAN sometimes hang the running process, so keep an eye open and restart if needed.

Источник

Get list of running processes with PHP

I want to get list of running processes for current user to assure if «file.php» is still running or not? I’m using cPanel and web server is Litespeed.

You need to do some proper research and actually make some attempts before posting. We’ll glad to help you with specific issues with your existing code. Currently, this question is way too broad.

It is possible to do it. However the solution is dependent on Operating System. Linux or Windows or other?

4 Answers 4

$execstring='ps -f -u www-data 2>&1'; $output=""; exec($execstring, $output); print_r($output); 

Will give you something like this

Array ( [0] => UID PID PPID C STIME TTY TIME CMD [1] => www-data 1587 790 0 14:04 ? 00:00:00 /usr/sbin/apache2 -k start [2] => www-data 7336 790 0 17:45 ? 00:00:00 /usr/sbin/apache2 -k start [3] => www-data 13426 16637 0 20:41 ? 00:00:00 sh -c ps -f -u www-data 2>&1 [4] => www-data 13427 13426 0 20:41 ? 00:00:00 ps -f -u www-data [5] => www-data 13428 22299 0 20:41 ? 00:00:00 sh -c ps -f -u www-data 2>&1 [6] => www-data 16412 790 0 15:19 ? 00:00:00 /usr/sbin/apache2 -k start [7] => www-data 16637 790 0 15:19 ? 00:00:00 /usr/sbin/apache2 -k start [8] => www-data 18977 790 0 06:25 ? 00:00:00 /usr/sbin/apache2 -k start [9] => www-data 18978 790 0 06:25 ? 00:00:00 /usr/sbin/apache2 -k start [10] => www-data 18979 790 0 06:25 ? 00:00:00 /usr/sbin/apache2 -k start [11] => www-data 18981 790 0 06:25 ? 00:00:00 /usr/sbin/apache2 -k start [12] => www-data 18983 790 0 06:25 ? 00:00:00 /usr/sbin/apache2 -k start [13] => www-data 19735 1 0 15:39 ? 00:00:00 php sql_runner.php [14] => www-data 22299 1 13 Mar23 ? 1-02:30:32 php scheduler.php [15] => www-data 22768 790 0 06:38 ? 00:00:00 /usr/sbin/apache2 -k start ) 

No you can filter/search with regex for your file.

Источник

Читайте также:  Настройка active directory astra linux
Оцените статью
Adblock
detector