PHP.mk документација

proc_terminate

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.proc-terminate.php PHP.net прокси Преводот е вчитан
Оригинал на PHP.net
Патека function.proc-terminate.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + преведен приказ Кодовите, табелите и белешките остануваат читливи во истиот тек.
proc_terminate

Референца за `function.proc-terminate.php` со подобрена типографија и навигација.

function.proc-terminate.php

proc_terminate

класата mysqli_driver

proc_terminateУбива процес отворен со proc_open

= NULL

proc_terminate(resource $process, int $signal = 15): bool

Сигнализира на process (креиран со proc_open()) дека треба да се прекине. proc_terminate() се враќа веднаш и не чека процесот да заврши.

proc_terminate() ви овозможува да го прекинете процесот и да продолжите со други задачи. Може да го проверите процесот (за да видите дали веќе завршил) со користење на proc_get_status() function.

Параметри

process

На proc_open() resource што ќе бидат затворени.

signal

Овој опционален параметар е корисен само на POSIX оперативни системи; може да специфицирате сигнал што ќе се испрати до процесот користејќи го kill(2) системски повик. Стандардно е SIGTERM.

Вратени вредности

Враќа статус на завршување на процесот што бил извршен.

Види Исто така

  • proc_open() - Изврши команда и отвори покажувачи на датотеки за влез/излез
  • proc_close() - Затвори процес отворен со proc_open и врати излезен код на тој процес
  • proc_get_status() - Добиј информации за процес отворен со proc_open

Белешки од корисници 4 белешки

csh точка спам на мене точка ком
12 години пред
/bin/sh -c CMD will fork sh and then exec CMD.
/bin/sh -c exec CMD will NOT fork and only executes CMD.

Therefore, you can get rid of this hack by prefixing your command to "exec bla bla bla".
jerhee на ucsd точка еду
пред 18 години
As explained in http://bugs.php.net/bug.php?id=39992, proc_terminate() leaves children of the child process running. In my application, these children often have infinite loops, so I need a sure way to kill processes created with proc_open(). When I call proc_terminate(), the /bin/sh process is killed, but the child with the infinite loop is left running. 

Until proc_terminate() gets fixed, I would not recommend using it. Instead, my solution is to:
1) call proc_get_status() to get the parent pid (ppid) of the process I want to kill. 
2) use ps to get all pids that have that ppid as their parent pid
3) use posix_kill() to send the SIGKILL (9) signal to each of those child pids
4) call proc_close() on process resource

<?php
$descriptorspec = array(
0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
2 => array('pipe', 'w')   // stderr is a pipe the child will write to
);
$process = proc_open('bad_program', $descriptorspec, $pipes);
if(!is_resource($process)) {
    throw new Exception('bad_program could not be started.');
}
//pass some input to the program
fwrite($pipes[0], $lots_of_data);
//close stdin. By closing stdin, the program should exit
//after it finishes processing the input
fclose($pipes[0]);

//do some other stuff ... the process will probably still be running
//if we check on it right away

$status = proc_get_status($process);
if($status['running'] == true) { //process ran too long, kill it
    //close all pipes that are still open
    fclose($pipes[1]); //stdout
    fclose($pipes[2]); //stderr
    //get the parent pid of the process we want to kill
    $ppid = $status['pid'];
    //use ps to get all the children of this process, and kill them
    $pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid $ppid`);
    foreach($pids as $pid) {
        if(is_numeric($pid)) {
            echo "Killing $pid\n";
            posix_kill($pid, 9); //9 is the SIGKILL signal
        }
    }
        
    proc_close($process);
}

?>
v точка denegin на yahoo точка ком
12 години пред
on Windows platform proc_terminate() does not kill sub-processes that are not handling kill signals. It happens even if you call xxx.exe and call proc_terminate() the process will remain active.

The solution is instead of calling proc_terminate() is to call the user-defined kill() function (already win/unix optimized)
After that need to close all pipes and execute proc_close().

function kill($pid){ 
    return stripos(php_uname('s'), 'win')>-1  ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");
}

function killall($pids) { 
    $os=stripos(php_uname('s'), 'win')>-1;
    ($_=implode($os?' /PID ':' ',$pids)) or ($_=$pids);
    return preg_match('/success|close/', $os ? exec("taskkill /F /T /PID $_") : exec("kill -9 $_"));
}

Example:

$pstatus = proc_get_status($resource);
$PID = $pstatus['pid'];

// other commands

kill($PID); // instead of proc_terminate($resource);
fclose($pipes[0]); 
fclose($pipes[1]); 
fclose($pipes[2]);
proc_close($resource);
smcbride на msn точка com
пред 5 години
Just a small note so people don't have to look elsewhere

To get the list of processes or find a process by name, use
$proclist = shell_exec('ps -elF') for linux
$proclist = shell_exec('tasklist') for windows

After that, you can use php normal parsing functions to get the pid
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.