Php get pid info

How to get PID from PHP function exec() in Windows?

(using php) Solution 1: I’m using Pstools which allows you to create a process in the background and capture it’s pid: It’s a little hacky, but it gets the job done Solution 2: I landed here thanks to google and decided that this ten years old post needs more info based on How to invoke/start a Process in PHP and kill it using Process ID. You can run the command in background but what is the pid of that Process?

How to get PID from PHP function exec() in Windows?

$pid = exec("/usr/local/bin/php file.php $args > /dev/null & echo \$!"); 

But I am using an XP virtual machine to develop a web app and I have no idea how to get the pid in windows.

C:\\wamp\\bin\\php\\php5.2.9-2\\php.exe "file.php args" > NUL & echo $! 

And it gets the file executed, but the output is «$!»

How can I get the pid into the var $pid? (using php)

I’m using Pstools which allows you to create a process in the background and capture it’s pid:

// use psexec to start in background, pipe stderr to stdout to capture pid exec("psexec -d $command 2>&1", $output); // capture pid on the 6th line preg_match('/ID (\d+)/', $output[5], $matches); $pid = $matches[1]; 

It’s a little hacky, but it gets the job done

Читайте также:  Setting maximum heap size in java

I landed here thanks to google and decided that this ten years old post needs more info based on How to invoke/start a Process in PHP and kill it using Process ID.

Imagine that you want to execute a command (this example uses ffmpeg to stream a file on a windows system to a rtmp server). You could command something like this:

ffmpeg -re -i D:\wicked_video.mkv -c:v libx264 -preset veryfast -b:v 200k -maxrate 400k -bufsize 6000k -pix_fmt yuv420p -g 50 -c:a aac -b:a 160k -ac 2 -ar 44100 -f flv rtmp:///superawesomestreamkey > d:\demo.txt 2> d:\demoerr.txt 

The first part is explained here and the last part of that command outputs to files with that name for logging purposes:

So lets assume that that command works. You tested it. To run that command with php you can execute it with exec but it will take time (another subject, check set_time_limit), its a video handled by ffmpeg via php. Not the way to go but it is happening in this case.

You can run the command in background but what is the pid of that Process? We want to kill it for some reason and psexec gives only the ‘process ID» runned by a user. And there is only one user in this case. We want multiple processes on the same user.

Here is a example to get the pid of a runned process in php:

// the command could be anything: // $cmd = 'whoami'; // This is a f* one, The point is: exec is nasty. // $cmd = 'shutdown -r -t 0'; // // but this is the ffmpeg example that outputs seperate files for sake $cmd = 'ffmpeg -re -i D:\wicked_video.mkv -c:v libx264 -preset veryfast -b:v 200k -maxrate 400k -bufsize 6000k -pix_fmt yuv420p -g 50 -c:a aac -b:a 160k -ac 2 -ar 44100 -f flv rtmp://10.237.1.8/show/streamkey1 > d:\demo.txt 2> d:\demoerr.txt'; // we assume the os is windows, pipe read and write $descriptorspec = [ 0 => ["pipe", "r"], 1 => ["pipe", "w"], ]; // start task in background, when its a recource, you can get Parent process id if ( $prog = is_resource( proc_open("start /b " . $cmd, $descriptorspec, $pipes ) ) ) < // Get Parent process Id $ppid = proc_get_status($prog); // this is the 'child' pid $pid = $ppid['pid']; // use wmic to get the PID $output = array_filter( explode(" ", shell_exec("wmic process get parentprocessid,processid | find \"$pid\"" ) ) ); array_pop($output); // if pid exitst this will not be empty $pid = end($output); // outputs the PID of the process echo $pid; >

The code above should echo the pid of the ‘inBackground’ runned process.

Note that you need to save the pid to kill it later if it is still running.

Now you can do this to kill the process: (imagine the pid is 1234)

//'F' to Force kill a process exec("taskkill /pid 1234 /F"); 

Here is my first post ever here on stackoverflow, I hope this will help someone. Have a awesome and not lonely christmas ♪♪

You will have to install an extra extension, but found the solution located at Uniformserver’s Wiki.

After some searching you might look into tasklist which coincidently, you may be able to use with the PHP exec command to get what you are after.

Here’s a somewhat less «hacky» version of SeanDowney’s answer.

PsExec returns the pid of the spawned process as its integer exit code. So all you need is this:

&1', $output, $pid); return $pid; > // spawn echo spawn('phpinfo.php'); ?> 

The -accepteula argument is needed only the first time you run PsExec, but if you’re distributing your program, each user will be running it for the first time, and it doesn’t hurt anything to leave it in for each subsequent execution.

PSTools is a quick and easy install (just unzip PSTools somewhere and add its folder to your path), so there’s no good reason not to use this method.

Php — getting cron specific pid, Get internal docker PID by system PID Hot Network Questions Identify this American novel set in the Great Depression era, perhaps set in Chicago and focused on meat packing?

PHP get PID of process and kill it

I’ve got a script to download a torrent file i’m using ctorrent which doesn’t seem to close itself so i need to kill the pid.

$command = "ctorrent -x \"/var/www/html/torrents/$torrentName\""; $output = shell_exec($command); 

This works perfectly, i saw on another stackoverflow question someone said to do the following:

$command = 'yourcommand' . ' > /dev/null 2>&1 & echo $!; '; $pid = exec($command, $output); var_dump($pid); 

but when i use this it removes the output of the downloading file part which i need as im getting some data from the output.

How can i just get the pid from running my script?

This is ultimately what i’m trying to achieve:

Just try the pgrep command.

$command = "pgrep programname"; $pid = shell_exec($command); 

I would suggest the following solution:

$command = 'ctorrent -x "/var/www/html/torrents/'.$torrentName.'"'; $outputfile = "output.out"; $pidfile = "pidfile.pid"; exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $command, $outputfile, $pidfile)); $pid = file_get_contents($pidfile); $outout = file_get_contents($outputfile); 

You can kill the process as you wrote:

This is the way i did it in the end, thanks for everyone’s advice, i noticed when i did what ineersa said and put . ‘ & echo $!; ‘; at the end it would add the PID at the start of my output text, So then i just captured the first line of the output and it works great.

$command = "ctorrent -x \"/var/www/html/torrents/$torrentName\""; $output = shell_exec($command); echo "
"; echo $output; echo "

"; $pid = strtok($output, "\n"); echo $pid;

How to get id from URL using php, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

PHP: get PID of a specific process

I have a QNAP box, that runs a flavor of linux and I am having problems getting the pid of a process using a php script. What I have so far:

$command = "PATH=$PATH:/share/MD0_DATA/.qpkg/Optware/bin: nohup /opt/bin/plowdown -o /share/MD0_DATA/Qdownload/plowshare http://www.megaupload.com/?d=m7duotr1 2> /share/MD0_DATA/Qdownload/plowshare/outputeeds.txt > /dev/null &"; exec($command, $out); $result = $out[0]; echo $result; 

If I run the command through PUTTY, I get:

[~] # nohup /opt/bin/plowdown -o /share/MD0_DATA/Qdownload/plowshare http://www.megaupload.com/?d=m7duotr1 2> /share/MD0_DATA/Qdownload/plowshare/outputteeds.txt > /dev/null & 22526 

The shell does not normally print the PID of a process it starts in background, unless it’s interactive. Otherwise, you would get tons of output during bootup just from the PIDs of all the processes that get started.

So you need to make the shell print the PID. Do

 exec("(PATH=$PATH:/share/MD0_DATA/.qpkg/Optware/bin: " . "nohup /opt/bin/plowdown -o /share/MD0_DATA/Qdownload/plowshare " . "http://www.megaupload.com/?d=m7duotr1 2> " . "/share/MD0_DATA/Qdownload/plowshare/outputeeds.txt > /dev/null &);" . "echo $$;", $out); 

Process — How to check whether specified PID is, It’s the same to kill -0 PID on shell, and shell_exec(‘kill -0 PID’) on PHP but NO ERROR output when pid is not exists. In forked child process, the posix_getpgid return parent’s pid always even if parent was terminated.

Executing and get pid a background process in PHP on Windows

I started a process in background in Windows apache server.

At that time, I want to get pid which php -f test.php . When I start index.php, I can see new php.exe process in output of tasklist command line. How can I get pid for this background process.

This will output the ProcessID after the task has been executed using wmic . You could then store this in a session or cookie to pass between pages.

$cmd = 'wmic process call create "C:/xampp/php/php.exe -f /path/to/htdocs/test.php" | find "ProcessId"'; $handle = popen("start /B ". $cmd, "r"); $read = fread($handle, 200); //Read the output echo $read; //Store the info pclose($handle); //Close 

PHP MySQL Get Last Inserted ID, Get ID of The Last Inserted Record. If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately. In the table «MyGuests», the «id» column is an AUTO_INCREMENT field: The following examples are equal to the examples from …

Источник

getmypid

Возвращает идентификатор процесса PHP или false в случае возникновения ошибки.

Примечания

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

Смотрите также

  • getmygid() — Получить GID владельца скрипта PHP
  • getmyuid() — Получение UID владельца скрипта PHP
  • get_current_user() — Получает имя владельца текущего скрипта PHP
  • getmyinode() — Получает значение inode текущего скрипта
  • getlastmod() — Получает время последней модификации страницы

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

Источник

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