Посмотреть все процессы php

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).

Читайте также:  Php string starts with numbers

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 ();
>

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Retrieves process list in a platform-independent way

christian-vigh-phpclasses/ProcessList

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

The ProcessList class provides a platform-independent way to retrieve the list of processes running on your systems. It works both on the Windows and Unix platforms.

To retrieve the list of processes currently running on your system, simply use the following :

require ( 'ProcessList.phpclass' ) ; $ps = new ProcessList ( ) ; 

The $ps variable can now be accessed as an array to retrieve process information, which is simply an object of class Process :

foreach ( $ps as $process ) echo ( "PID : ProcessId>, COMMAND : Command>" ) ; 

Whether you are running on Windows or Unix, the properties exposed by the Process objects remain the same (see the Reference section).

For Windows platforms, you will need the following package :

http://www.phpclasses.org/package/10001-PHP-Provides-access-to-Windows-WMI.html 

A copy of the source code is provided here for your convenience, but it may not be the latest release.

The ProcessList class is a container class that allows you to retrieve information about individual processes. It implements the ArrayAccess and Iterator interfaces, so that you can loop through each process currently running on your system.

Each element of a ProcessList array is an object of class Process.

public function __construct ( $load = true ) ; 

Creates a process list object. If the $load parameter is true, the process list will be retrieved ; otherwise, you will need to call the Refresh() method later before looping through the list of available processes.

public function GetProcess ( $id ) ; 

Searches for a process having the specified $id.

Returns an object of class Process if found, or false otherwise.

public function GetProcessByName ( $name ) ; 

Searches for a process having the specified name. The name is given by the Command property of the Process object.

public function GetChildren ( $id ) ; 

Returns the children of the specified process, or an empty array if $id does not specify a valid process id.

Refreshes the current process list. This function can be called as many times as desired on the same ProcessList object.

The Process class does not contain methods, but simply expose properties that contain information about a process.

Contains the command-line arguments of the process. As for C (and PHP) programs, Argv[0] represents the command path.

Command name, without its leading path.

Full command line, including arguments.

CPU time consumed by the process, in the form «hh:mm:ss».

Dd of the parent process for this process.

Process id of the current process.

Process start time, in the form «yyyy-mm-dd hh:mm:ss».

Process title. On Windows systems, it will be the title of the process. Since there is no notion of process title on Unix systems, it will be set to the value of the Command property.

Attached tty. This information is useful mainly for Unix systems.

User name running the process. On Unix systems, this can be either a user name or a user id.

About

Retrieves process list in a platform-independent way

Источник

Как получить список запущенных 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, а затем сравнить с запущенными процессами.

Ещё вопросы

  • 1 Как получить ButtonDrawable из флажка в API 21?
  • 0 Как создать функцию / процедуру в MariaDB для запуска сценария обновления при доступе к таблице?
  • 1 Как я могу сохранить hourOfDay и минуты из timePickerDialog, чтобы сравнить его с какой-то другой переменной?
  • 0 .HTACCESS — Дамп сайт от производства до разработки
  • 0 Qt mac переключается между панелями без изменения окна
  • 0 Код ошибки: 1452 не может добавить или обновить дочернюю строку, ограничение внешнего ключа завершается ошибкой MySQL
  • 1 Подсчитать количество экземпляров строки в очень большом массиве и добавить значение к значению хеша
  • 1 Каждый из next () и list () перебирает генератор с изменяемым объектом по-разному
  • 1 Интернационализация с весны MVC
  • 1 Настройка SFML.net 2.1?
  • 1 React-Native добавляет var в тег просмотра
  • 1 Свободный запрос за пределами просроченного соединения
  • 0 Проблема с повторяющимися кнопками поля формы
  • 0 AngularJS: поделиться общей фабрикой для создания нового объекта
  • 0 получение данных с сервера в формате xml
  • 0 Как работать с аргументами в Xcode
  • 1 Какой самый быстрый и простой способ связи между двумя процессами в C #?
  • 0 Соединить две таблицы подзапроса
  • 1 Лучшее использование абстрактных классов переопределения в приложении
  • 1 Приложение со встроенным API Google Cloud Vision аварийно завершает работу с нулевой ссылкой на объект
  • 1 Spring Security Вход в систему
  • 1 Примените UDF к подмножествам pyspark dataframe
  • 1 Объединение листов Excel в несколько циклов
  • 0 вставлять и удалять целые числа на лету
  • 1 Как контролировать отображение окон tkinter Toplevel?
  • 1 Преобразование миллисекунд в объект даты UTC с часовым поясом UTC
  • 0 страница переходит наверх при нажатии меню
  • 0 Разрывы строк на основе длины текста с сохранением пользовательской разметки HTML
  • 0 Зависимости Бауэра для Angular в Eclipse
  • 0 Изменить первичные ключи массива
  • 0 Рекурсивно создать дерево
  • 0 Qt ActiveX извлекает количество страниц в текстовом документе
  • 0 Почему я не могу загрузить значения базы данных в мой список?
  • 1 как создать делегата на целевой класс
  • 1 Секунда весны: перехватить URL-адрес легко обойти?
  • 0 Как выбрать в MySQL данные | xx | xx | xx |
  • 0 Sql запрос Join / Где 3 таблицы
  • 1 Android MVVM и Retrofit api — нулевой ответ
  • 1 WP8 BUG: несоответствие идентификатора подписи кода при установке из хаба компании
  • 1 Angular CLI использует SystemJS?
  • 1 Arduino мигает светодиод на нажатой кнопке приложения c #
  • 0 Как манипулировать массивом, чтобы он возвращался как структура json в PHP?
  • 0 Изображения появляются в Chrome, но не в IE
  • 1 Пандейские рассуждения о способе условного обновления нового значения из других значений в той же строке в DataFrame
  • 1 Поиск слова в списке
  • 0 Как получить доступ к данным $ _POST для нескольких форм
  • 1 Ошибка рекурсии при получении переполнения стека с обнаружением коллизий
  • 1 C # Получить разницу между двумя датами DateTime [дубликаты]
  • 0 Ошибка основного дампа связанного списка C ++
  • 1 Изменение состояния веб-приложения во время выполнения

Источник

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