[TOC]
* * * * *
## 1 PCNTL進程控制
### 1 簡介
進程控制PCNTL實現了unix方式的進程操作
不能用于web服務器環境模式
只使用于unix平臺
### 2 使用
~~~
<?php
//定義ticks
declare( ticks = 1 );
//產生子進程分支
$pid = pcntl_fork ();
if ( $pid == - 1 ) {
//pcntl_fork返回-1標明創建子進程失敗
die( "could not fork" );
} else if ( $pid ) {
//父進程中pcntl_fork返回創建的子進程進程號
exit();
} else {
// 子進程pcntl_fork返回的時0
}
// 從當前終端分離
if ( posix_setsid () == - 1 ) {
die( "could not detach from terminal" );
}
// 安裝信號處理器
pcntl_signal ( SIGTERM , "sig_handler" );
pcntl_signal ( SIGHUP , "sig_handler" );
// 執行無限循環任務
while ( 1 ) {
// 等待用戶操作請求
}
function sig_handler ( $signo )
{
switch ( $signo ) {
case SIGTERM :
// 處理中斷信號
exit;
break;
case SIGHUP :
// 處理重啟信號
break;
default:
// 處理所有其他信號
}
}
?>
~~~
### 3 函數接口
#### pcntl_fork() 創建子進程
`int pcntl_fork ( void )`
父進程返回子進程pid>0
子進程返回0
創建失敗父進程上下文返回-1
#### pcntl_singal() 安裝信號處理器
~~~
bool pcntl_signal ( int $signo , callback $handler [, bool $restart_syscalls = true ] )
~~~
> $signo:信號
> $handler:回調處理
為指定的信號創建回調處理函數
#### pcntl_signal_dispatch() 分發信號
將接受到的信號進行廣播分發
#### pcntl_wait() pcntl_waitpid()等待進程退出
`int pcntl_wait ( int &$status [, int $options = 0 ] )`
> $status: 獲取子進程退出的狀態信息
> $options:
>> WNOHANG 如果沒有子進程退出立刻返回。
>> WUNTRACED 子進程已經退出并且其狀態未報告時返回。
掛起當前進程直到一個子進程退出
或接受到一個信號要求中斷當前進程
或調用一個信號處理函數
`int pcntl_waitpid ( int $pid , int &$status [, int $options = 0 ] )`
> $pid: 等待進程id
>> [< -1] 等待任意進程組ID等于參數pid給定值的絕對值的進程。
> [-1] 等待任意子進程;與pcntl_wait函數行為一致。
> [0] 等待任意與調用進程組ID相同的子進程。
> [> 0] 等待進程號等于參數pid值的子進程。
掛起當前進程直到pid指定的進程號的進程退出
或接受到一個信號要求中斷當前進程
或調用一個信號處理函數
#### pcntl_exex() 當前進程執行指定的程序
`void pcntl_exec ( string $path [, array $args [, array $envs ]] )`
> $path: 可執行程序路徑
> $args: 參數數組
> $envs: 環境變量數組
當前進程運行指定可執行文件
#### pcntl_alarm() 設置一個alarm鬧鐘信號
`int pcntl_alarm ( int $seconds )`
> $seconds:定時時間秒數
在指定的秒數后向進程發送一個 SIGALRM 信號
每次對 pcntl_alarm() 的調用都會取消之前設置的alarm信號
可以用來實現計時器
返回alarm調度剩余的描述,沒有alarm調度返回0
## 2 POSIX標準接口
>[info] 當前進程操作
~~~
posix_getpid()
返回當前進程的進程id
posix_getppid()
返回當前進程的父進程id
posix_getpgrp()
返回當前進程的進程組id
posix_getgid()
返回當前進程的gid
posix_setgid()
設置當前進程的gid
posix_getgroups()
返回當前進程的進程組集合
~~~
>[info] 當前進程其他操作
~~~
posix_times()
返回當前進程cpu耗時
posix_getuid()
返回當前進程的用戶id
posix_getegid()
返回當前進程的有效gid
posix_setegid()
設置當前進程的有效gid
posix_geteuid()
返回當前進程的有效uid
posix_seteuid()
設置當前進程的有效uid
posix_getpgid()
獲取進程的pgid
posix_setpgid()
設置進程的pgid
posix_getsid()
獲取進程的當前會話id
posix_setsid()
設置進程的當前會話id
posix_getgrgid()
獲取進程組的信息
posix_getgrnam()
獲取進程組的信息
posix_getpgid()
返回進程的進程組
posix_getsid()
返回進程的會話id
~~~
>[info] 用戶信息操作
~~~
posix_getlogin()
獲取登錄用戶名
posix_getpwnam()
獲取指定用戶信息
posix_getwuid()
獲取指定用戶信息
~~~
>[info] 文件操作
~~~
posix_access()
設置文件權限模式
posix_ctermid()
獲取控制器終端當前路徑
posix_getcwd()
獲取當前目錄信息
posix_mkfifo()
posix_mknod()
~~~
>[info] 其他操作
~~~
posix_kill() 發送sig信號到pid進程
posix_uname() 獲取系統名稱
posix_ttyname() 設置終端設備名稱
posix_strerror() 輸出錯誤代號
posix_getrlimit() 獲取系統資源限制
~~~
## 3 執行外部程序
~~~
exec()
passthru()
shell_exec()
system()
proc_open()
proc_terminate()
proc_nice()
proc_get_status()
proc_close()
~~~