1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
| namespace app\autotask;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use think\Log;
class Demo extends Command
{
const SHARE_SIZE = 1024;
protected function configure()
{
//设置参数
$this->addArgument('act', Argument::REQUIRED); //必传参数
//帮助文档中的命令备注
$this->setName('demo')->setDescription('Here is the remark of autotask-demo');
}
/**
* 可以这样执行命令 php think demo start|stop|status
* @param Input $input
* @param Output $output
*/
protected function execute(Input $input, Output $output)
{
//获取参数值
$args = $input->getArguments();
if(!in_array($args['act'],['start','stop','status'])){
$output->writeln('Unknow args!');
}
switch ($args['act']){
case 'start':
$res = $this->setRuningStatus(true);
if($res){
$msg ='Demo start success!';
}else{
$msg ='Demo start fail!';
}
break;
case 'stop':
$res = $this->setRuningStatus(false);
if($res){
$msg ='Demo stop success!';
}else{
$msg ='Demo stop fail!';
}
break;
case 'status':
$population = $this->getRuningStatus();
if($population===false){
$status = 'notfound';
}elseif($population===1){
$status = 'start';
}elseif($population===2){
$status = 'stop';
}else{
$status = 'unknow';
}
$msg = "The Demo's status is ".$status;
break;
}
$output->writeln($msg);
if($args['act']=='start' && $res){
$this->keepStart();
}
}
protected function getRuningStatus()
{
$shmop_key = $this->getShmopKey();
if($shmop_key==-1){
return false;
}
$shmop_id = shmop_open($shmop_key,'w',0,self::SHARE_SIZE);
$shmop_size = shmop_size($shmop_id);
$population = shmop_read($shmop_id,0, $shmop_size);
shmop_close($shmop_id);
return $population;
}
protected function setRuningStatus($start)
{
$shmop_key = $this->getShmopKey();
if($shmop_key==-1){
return false;
}
$shmop_id = shmop_open($shmop_key,'c',0644,self::SHARE_SIZE);
if($start===true){
$population = 1;
}else{
$population = 2;
}
$shmop_bytes_written = shmop_write($shmop_id, $population,0);
shmop_close($shmop_id);
if ($shmop_bytes_written != strlen($population)) {
return false;
} else {
return true;
}
}
protected function getShmopKey()
{
if(!function_exists('ftok')) {
$shmop_key = myftok(__FILE__, 23);
}else{
$shmop_key = ftok(__FILE__,'p');
}
return $shmop_key;
}
protected function keepStart()
{
$output = new Output;
while (true){
if($this->getRuningStatus()!==1) {
$res = $this->setRuningStatus(true);
if($res){
$msg ='Demo auto start success!';
}else{
$msg ='Demo auto start fail!';
}
$output->writeln($msg);
}else{
sleep(3);
}
}
}
}
|