sapi/cgi/php-cgi,sapi/cgi/php-cgi

PHP不一定要以http方式调用。PHP与其它应用的接口叫做SAPI,选用不同的SAPI决定了调用PHP的方式。例如Apache的mod_php就是一个SAPI的实现,用于Apache与PHP交互,同样,CGI和FastCGI(如fpm)的SAPI实现也是用于以HTTP方式调用PHP解释器。除此之外,还有很多SAPI,如CLI的SAPI可以支持命令行方式运行PHP脚本,运用php的pcntl_fork函数可以用与C类似的方式(两次fork)创建deamon进程,这样PHP脚本就可以当做服务使用了。至于服务与其它进程的交互,php支持socket。我写过一个小的Demo,展示了如何用PHP写Server,你可以看一下:

//Accpet the http client request and generate response content.

//As a demo, this function just send "PHP HTTP Server" to client.

function handle_http_request($address, $port)

{

$max_backlog = 16;

$res_content = "HTTP/1.1 200 OK\nContent-Length: 15\nContent-Type: text/plain; charset=UTF-8\n\nPHP HTTP Server

";

$res_len = strlen($res_content);

//Create, bind and listen to socket: 127.0.0.1:8888

if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE)

{

echo "Create socket failed!\n";

exit;

}

if((socket_bind($socket, $address, $port)) === FALSE)

{

echo "Bind socket failed!\n";

exit;

}

if((socket_listen($socket, $max_backlog)) === FALSE)

{

echo "Listen to socket failed!\n";

exit;

}

//Loop

while(TRUE)

{

if(($accept_socket = socket_accept($socket)) === FALSE)

{

continue;

}

else

{

socket_write($accept_socket, $res_content, $res_len);

socket_close($accept_socket);

}

}

}

//Run as deamon process.

function run()

{

if(($pid1 = pcntl_fork()) === 0)

//First child process

{

posix_setsid(); //Set first child process as the session leader.

if(($pid2 = pcntl_fork()) === 0)

//Second child process, which run as deamon.

{

handle_http_request('www.codinglabs.org', 9999); //Replaced by your own domain or address.

}

else

{

//Second child process exit;

exit;

}

}

else

{

//First child process exit;

pcntl_wait($status);

}

}

//Entry point.

run();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值