getmypid
(PHP 4, PHP 5, PHP 7, PHP
getmypid — Gets PHP’s process ID
Description
Parameters
This function has no parameters.
Return Values
Returns the current PHP process ID, or false
on error.
Notes
Warning
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
Found A Problem?
Radu Cristescu ¶
11 years ago
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).
#!/usr/bin/php
<?php
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);
exit(
0);
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();
}
return
false;
}
?>
Robert Mays Jr ¶
14 years ago
All of the examples above require you to have shell command execution turned on- this example uses only PHP functions and should work on any system (posix is included by default)-
the key is posix_getsid which will return FALSE if the processes does not exist.
<?php
$lockfile = sys_get_temp_dir() . '/myScript.lock';
$pid = file_get_contents($lockfile);
if (posix_getsid($pid) === false) {
print "process has died! restarting...\n";
file_put_contents($lockfile, getmypid()); // create lockfile
} else {
print "PID is still alive! can not run twice!\n";
exit;
}
?>
:-) perfect if you need to make sure a cron job or shell script has ended before it can be started again.
This works across users- if the cron job is started as 'root' your 'web user' can see if the process is still alive (useful for system status pages)
brospam at gmail dot com ¶
11 years ago
My lockfile system
<?php
function isLocked(){
if(file_exists(LOCK_FILE)) {
$lockingPID = trim(file_get_contents(LOCK_FILE));
$test=trim(`ps -p $lockingPID -o pid=`);
if(!empty($test)) return true;
echo "Removing stale lock file.\n";
unlink(LOCK_FILE);
}
file_put_contents(LOCK_FILE, getmypid()."\n");
return false;
}
?>
Kevin Traas (ktraas- at -gmail dot com) ¶
15 years ago
Looking to create a lock-file mechanism for a cmd-line script?
Enjoy!
#!/usr/bin/php
<?php
define
( 'LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );
if( isLocked() ) die( "Already running.\n" );
# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);
unlink( LOCK_FILE );
exit(0);
function
isLocked()
{
# If lock file exists, check if stale. If exists and is not stale, return TRUE
# Else, create lock file and return FALSE.
if( file_exists( LOCK_FILE ) )
{
# check if it's stale
$lockingPID = trim( file_get_contents( LOCK_FILE ) );
# Get all active PIDs.
$pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );
# If PID is still active, return true
if( in_array( $lockingPID, $pids ) ) return true;
# Lock-file is stale, so kill it. Then move on to re-creating it.
echo "Removing stale lock file.\n";
unlink( LOCK_FILE );
}
file_put_contents( LOCK_FILE, getmypid() . "\n" );
return false;
}
?>
brooke at jump dot net ¶
21 years ago
One good use for this is deciding on a concurrency-safe temporary file or directory name. You can be assured that no two processes on the same server have the same PID, so this is enough to avoid collisions. For example:
<?php
$tmpfile = "/tmp/foo_".getmypid();
// Use $tmpfile...
// Use $tmpfile...
// Use $tmpfile...
unlink ($tmpfile);
?>
If you are sharing /tmp over the network (which is odd....) then you can, of course, mix in the PHP server's IP address.
ritaswc1 at gmail dot com ¶
18 days ago
// this is a async job process worker
file_put_content('job.log', "This worker's process ID is " . getmypid());
// send emails or make excel files
wouter99999 at gmail dot com ¶
13 years ago
On windows, ps is not available. Instead, to view a list of running processes, you can use exec('tasklist'); To kill processes you can use exec('taskkill); Enter taskkill /? for more information.
kroczu at interia dot pl ¶
19 years ago
<?php
/*
mixed getpidinfo(mixed pid [, string system_ps_command_options])
this function gets PID-info from system ps command and return it in useful assoc-array,
or return false and trigger warning if PID doesn't exists
$pidifo=getpidinfo(12345);
print_r($pidifo);
Array
(
[USER] => user
[PID] => 12345
[%CPU] => 0.0
[%MEM] => 0.0
[VSZ] => 1720
[RSS] => 8
[TT] => ??
[STAT] => Is
[STARTED] => 6:00PM
[TIME] => 0:00.01
[COMMAND] => php someproces.php > logfile
)
*/
//////////////////////////////////////////////
function getpidinfo($pid, $ps_opt="aux"){
$ps=shell_exec("ps ".$ps_opt."p ".$pid);
$ps=explode("\n", $ps);
if(
count($ps)<2){
trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING);
return false;
}
foreach(
$ps as $key=>$val){
$ps[$key]=explode(" ", ereg_replace(" +", " ", trim($ps[$key])));
}
foreach(
$ps[0] as $key=>$val){
$pidinfo[$val] = $ps[1][$key];
unset($ps[1][$key]);
}
if(
is_array($ps[1])){
$pidinfo[$val].=" ".implode(" ", $ps[1]);
}
return $pidinfo;
}
?>
eight_hf at live dot fr ¶
12 years ago
On Linux you can check if a process is still running by verifying if the PID exists in the /proc directory :
<?php
if(file_exists('/proc/'.$pid))
{
echo 'The process is still running.';
}
?>
Erickson Reyes ercbluemonday at yahoo dot com ¶
15 years ago
We also had this challenge in our company to prevent a php script in a cron job from overlapping each other.
We made this solution
<?php
// Initialize variables
$found = 0;
$file = basename(__FILE__);
$commands = array();// Get running processes.
exec("ps w", $commands);// If processes are found
if (count($commands) > 0) {
foreach (
$commands as $command) {
if (strpos($command, $file) === false) {
// Do nothin'
}
else {
// Let's count how many times the file is found.
$found++;
}
}
}// If the instance of the file is found more than once.
if ($found > 1) {
echo "Another process is running.\n";
die();
}/**
*
* Regular process here...
*
*/
?>
pdc at example dot com ¶
13 years ago
Here is how you'd use exec on a posix system to accomplish counting processes quickly.
I want to know how many processes are running with 'update.php' in the command:
ps aux|grep "[u]pdate.php"|wc -l
(the trick of using [u]pdate.php instead of update.php makes sure that the grep command itself is not matched). Be sure to use quotes in the command, or it won't work either.
So, the code:
<?php
function countProcesses($scriptName)
{
// ps aux|grep "[u]pdate.php"|wc -l
$first = substr($scriptName, 0, 1);
$rest = substr($scriptName, 1);
$name = '"['.$first.']'.$rest.'"';
$cmd = "ps aux | grep $name | wc -l";
$result = exec($cmd);
return
$result;
}
?>
martijn at nowhere dot com ¶
9 years ago
On windows, you can get a list of PID's using this single line statement: <?php $pids = array_column(array_map('str_getcsv', explode("\n",trim(`tasklist /FO csv /NH`))), 1); ?>.
Pure-PHP ¶
20 years ago
You can use this function also to avoid more than one instance of your app.
You can also use this class.
http://www.pure-php.de/node/20
Usage:
<?php
inlude
("ProcessHandler.class.php");
if(
ProcessHandler::isActive()){
die("Already running!\n";);
}else{
ProcessHandler::activate();
//run my app
}?>
gabe at fijiwebdesign dot com ¶
15 years ago
Based on what james at voodoo dot co dot uk said, but modified for CLI scripts (ie: there is no $_SERVER).
<?php/**
* Check for a current process by filename
* @param $file[optional] Filename
* @return Boolean
*/
function processExists($file = false) {$exists = false;
$file = $file ? $file : __FILE__;// Check if file is in process list
exec("ps -C $file -o pid=", $pids);
if (count($pids) > 1) {
$exists = true;
}
return $exists;
}?>
james at voodoo dot co dot uk ¶
15 years ago
The 'ps' command has an option that can make filtering for a specific process more efficient. Using this the work of looking for matching processes can be made neater:
<?php
/*
Return an array of the pids of the processes that are running for the specific command
e.g.
returnPids('myprocess.php');
*/
function returnPids($command) {
exec("ps -C $command -o pid=",$pids);
foreach ($pids as $key=>$value) $pids[$key]=trim($value);
return $pids;
} /*
Returns an array of the pids for processes that are like me, i.e. my program running
*/
function returnMyPids() {
return returnPids(basename($_SERVER["SCRIPT_NAME"]));
}
?>
e.g. to bomb out if I'm running already
if (count(returnMyPids())>1) exit;
Просмотр процессов PHP
На сервере Zone процессы PHP можно отслеживать и изучать с помощью ряда инструментов. Одним из самых распространенных инструментов является команда ps
.
- Например, если вы хотите увидеть все процессы PHP:
ps aux | grep php
top
илиhtop
– это динамические инструменты, отображающие активные в данный момент процессы. Они также позволяют сортировать и фильтровать процессы по нагрузке, использованию памяти и т. д.
Как убить определенный процесс PHP
Если вам нужно убить определенный процесс PHP, сначала необходимо найти идентификатор процесса (PID). Это можно сделать, например, с помощью ps
/top
/htop
.
- Найдя идентификатор процесса, вы можете вручную убить его следующим образом:
kill <ID_процесса>
Принудительная приостановка процессов PHP
- Если вы хотите убить все процессы PHP одновременно, вы можете использовать следующую команду:
pkill -9 php
- Следующие команды подходят для завершения процессов в определенной версии PHP:
pkill -9 php83-cgi
илиkillall -9 php83-cgi
Updated on 30. Sep 2024
INTRODUCTION
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.
OVERVIEW
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 : {$process -> ProcessId}, COMMAND : {$this -> Command}" ) ;
Whether you are running on Windows or Unix, the properties exposed by the Process objects remain the same (see the Reference section).
DEPENDENCIES
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…
Reference
ProcessList class
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.
Constructor
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.
GetProcess
public function GetProcess ( $id ) ;
Searches for a process having the specified $id.
Returns an object of class Process if found, or false otherwise.
GetProcessByName
public function GetProcessByName ( $name ) ;
Searches for a process having the specified name. The name is given by the Command property of the Process object.
GetChildren
public function GetChildren ( $id ) ;
Returns the children of the specified process, or an empty array if $id does not specify a valid process id.
Refresh
public function Refresh ( ) ;
Refreshes the current process list. This function can be called as many times as desired on the same ProcessList object.
Process class
The Process class does not contain methods, but simply expose properties that contain information about a process.
Argv property
Contains the command-line arguments of the process. As for C (and PHP) programs, Argv[0] represents the command path.
Command
Command name, without its leading path.
CommandLine
Full command line, including arguments.
CpuTime
CPU time consumed by the process, in the form «hh:mm:ss».
ParentProcessId
Dd of the parent process for this process.
ProcessId
Process id of the current process.
StartTime
Process start time, in the form «yyyy-mm-dd hh:mm:ss».
Title
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.
Tty
Attached tty. This information is useful mainly for Unix systems.
User property
User name running the process. On Unix systems, this can be either a user name or a user id.
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .
Создаем SPA на C# и Blazor
stackOverflow 04.05.2025
Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .
Реализация шаблонов проектирования GoF на C++
NullReferenced 04.05.2025
«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .
C# и сети: Сокеты, gRPC и SignalR
UnmanagedCoder 04.05.2025
Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .
Создание микросервисов с Domain-Driven Design
ArchitectMsa 04.05.2025
Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .
Многопоточность в C++: Современные техники C++26
bytestream 04.05.2025
C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .