Виснет бесконечный php-скрипт при работе с сокетами

Автор lk1918, 09 марта 2015, 14:31:59

« назад - далее »

0 Пользователи и 1 гость просматривают эту тему.

lk1918

Добрый день!
Создал веб-сервер в виде связки nginx+apache+php-fpm. У меня есть бесконечный php-скрипт, который рассылает данные десктопным приложениям через сокеты. Однако, этот скрипт работает некоторое время и зависает. Грешу на неоптимальные настройки. Не могу понять, куда копать.
P.S. Прошу сильно не пинать ногами, ибо я новичок в администрировании дебиана  :)


lk1918

php script и конфиг из /etc/php5/fpm
Открыть содержимое (спойлер)

Код php

<?php
  $fh 
fopen(__FILE__'r');
  if( ! 
flock($fhLOCK_EX LOCK_NB) )
  {
       echo(
'Server is already running');
       die();
  }

  
set_time_limit(0);
  
ignore_user_abort(true);

  include(
"functions.php");
  include(
"dbconnect.php");

  
$address '0.0.0.0';
  
$port 38000;

  
$sock socket_create(AF_INETSOCK_STREAMSOL_TCP) or logging("Socket create error!",true);
  
logging("Server created");

  
socket_set_nonblock($sock);

  
socket_bind($sock$address$port) or logging("Socket bind error",true);
  
logging("Server binded");

  
socket_listen($sock5)or logging("Socket listen error",true);
  
logging("Server started");


  
$clients = array();
  
$client_ids = array();
  
$addrs = array();
  
$ports = array();

  
//$memindex = 0;

  
while(true)
  {

          
usleep(100000);
          
//if($memindex == 0)
          //{
          //           logging(memory_get_usage());
          //}
          //$memindex = fmod($memindex+1, 150);

          
$read=array();
          
$read[0] = $sock;
          
$write = array();
          
$except = array();

          foreach(
$clients as $cl$read[] = $cl;



          
$ready socket_select($read,$write,$except,0);

          if(
in_array($sock,$read))
          {
                  
$cl socket_accept($sock);
                  
$clients[] = $cl;
                  
$index array_search($cl,$clients);

                  
socket_getpeername($cl,$addr,$prt);
                  
$addrs[$index] = $addr;
                  
$ports[$index] = $prt;
                  
toSocket($cl,$addr,$prt,'<code>0</code><description>Connected</description>');


          }

          foreach(
$clients as $i => $cl)
          {
                  if(
in_array($cl,$read))
                  {
                          
logging($addrs[$i].':'.$ports[$i].'  Clients count : '.count($clients));
                          
$data = @socket_read($cl,7);
                          if(
$data === false)
                          {
                                  
logging($addrs[$i].':'.$ports[$i].' Disconnected by client');
                                  unset(
$clients[$i]);
                                  unset(
$client_ids[$i]);
                                  unset(
$addrs[$i]);
                                  unset(
$ports[$i]);
                                  continue;
                          }

                          elseif(
$data)
                          {
                                  
$len = (int)$data;
                                  
socket_recv($cl,$data,$len,MSG_WAITALL);

                                  
logging($addrs[$i].':'.$ports[$i].' Receive : '.$data);

                                  if(
$data == 'exit')
                                  {
                                        
logging($addrs[$i].':'.$ports[$i].' Stop server command');
                                        
toSocket($cl,$addrs[$i],$ports[$i],'OK');
                                        foreach(
$clients as $c)
                                              
socket_close($c);

                                        break 
2;
                                  }


                                  
$msg json_decode($data);
                                  if(!isset(
$msg->{'type'}))
                                      
toSocket($cl,$addrs[$i],$ports[$i],'<code>2</code><description>Invalid request type</description>');
                                  else
                                  {
                                        switch(
$msg->{'type'})
                                        {
                                                case 
0: {
                                                            include(
'ReceiverInit.php');
                                                            break;
                                                        }
                                                case 
1: {
                                                            
//toSocket($cl,$addrs[$i],$ports[$i],'OK');
                                                            
socket_close($cl);
                                                            
logging($addrs[$i].':'.$ports[$i].' Disconnected by server');
                                                            unset(
$clients[$i]);
                                                            unset(
$client_ids[$i]);
                                                            unset(
$addrs[$i]);
                                                            unset(
$ports[$i]);
                                                            include(
'ReceiverTranslateSignal.php');
                                                            break;
                                                        }
                                                case 
2: {
                                                            include(
'ReceiverCheck.php');
                                                            break;
                                                        }
                                                case 
3: {
                                                            include(
'ReceiverGetListOfSymbols.php');
                                                            break;
                                                        }
                                                case 
4: {
                                                            include(
'ReceiverGetUnknownSymbol.php');
                                                            break;
                                                        }
                                                default:{
                                                            
toSocket($cl,$addrs[$i],$ports[$i],'<code>2</code><description>Invalid request type '.$msg->{'type'}.'</description>');
                                                            break;
                                                        }
                                        }
                                  }

                          }


                  }
          }
       }

socket_close($sock);
logging("Server stopped");
mysql_close();

?>


php.ini

[PHP]
engine = On

short_open_tag = On

asp_tags = Off

precision = 14

output_buffering = 4096

zlib.output_compression = Off

implicit_flush = Off

unserialize_callback_func =

serialize_precision = 17

disable_functions = pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,

disable_classes =

zend.enable_gc = On

expose_php = On

max_execution_time = 0

max_input_time = 60

memory_limit = 128M

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

display_errors = Off

display_startup_errors = Off

log_errors = On

log_errors_max_len = 1024

ignore_repeated_errors = Off

ignore_repeated_source = Off

report_memleaks = On

track_errors = Off

html_errors = Off

variables_order = "GPCS"

request_order = "GP"

register_argc_argv = Off

auto_globals_jit = On

post_max_size = 8M

auto_prepend_file =

auto_append_file =

default_mimetype = "text/html"

doc_root =

user_dir =

enable_dl = Off

file_uploads = On

upload_max_filesize = 150M

max_file_uploads = 200

allow_url_fopen = On

allow_url_include = Off

default_socket_timeout = 120

[CLI Server]

cli_server.color = On

[Date]

[filter]

[iconv]

[intl]


[sqlite]


[sqlite3]

[Pcre]

[Pdo]

[Pdo_mysql]

pdo_mysql.cache_size = 2000

pdo_mysql.default_socket=

[Phar]

[mail function]

SMTP = localhost

smtp_port = 25

mail.add_x_header = On

[SQL]

sql.safe_mode = Off

[ODBC]

odbc.allow_persistent = On


odbc.check_persistent = On

odbc.max_persistent = -1

odbc.max_links = -1

odbc.defaultlrl = 4096


odbc.defaultbinmode = 1

[Interbase]

ibase.allow_persistent = 1

ibase.max_persistent = -1

ibase.max_links = -1

ibase.timestampformat = "%Y-%m-%d %H:%M:%S"

ibase.dateformat = "%Y-%m-%d"

ibase.timeformat = "%H:%M:%S"

[MySQL]

mysql.allow_local_infile = On

mysql.allow_persistent = On

mysql.cache_size = 2000

mysql.max_persistent = -1

mysql.max_links = -1

mysql.default_port =

mysql.default_socket =

mysql.default_host =

mysql.default_user =

mysql.default_password =

mysql.connect_timeout = 60

mysql.trace_mode = Off

[MySQLi]

mysqli.max_persistent = -1

mysqli.allow_persistent = On

mysqli.max_links = -1

mysqli.cache_size = 2000

mysqli.default_port = 3306

mysqli.default_socket =

mysqli.default_host =

mysqli.default_user =

mysqli.default_pw =

mysqli.reconnect = Off

[mysqlnd]

mysqlnd.collect_statistics = On

mysqlnd.collect_memory_statistics = Off

[OCI8]

[PostgreSQL]

pgsql.allow_persistent = On

pgsql.auto_reset_persistent = Off

pgsql.max_persistent = -1

pgsql.max_links = -1

pgsql.ignore_notice = 0

pgsql.log_notice = 0

[Sybase-CT]

sybct.allow_persistent = On

sybct.max_persistent = -1

sybct.max_links = -1

sybct.min_server_severity = 10

sybct.min_client_severity = 10

[bcmath]

bcmath.scale = 0

[browscap]

[Session]

session.save_handler = files

session.use_cookies = 1

session.use_only_cookies = 1

session.name = PHPSESSID

session.auto_start = 0

session.cookie_lifetime = 0

session.cookie_path = /

session.cookie_domain =

session.cookie_httponly =

session.serialize_handler = php

session.gc_probability = 0

session.gc_divisor = 1000

session.gc_maxlifetime = 1440

session.referer_check =

session.cache_limiter = nocache

session.cache_expire = 180

session.use_trans_sid = 0

session.hash_function = 0

session.hash_bits_per_character = 5

url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"

[MSSQL]

mssql.allow_persistent = On

mssql.max_persistent = -1

mssql.max_links = -1

mssql.min_error_severity = 10

mssql.min_message_severity = 10

mssql.compatability_mode = Off

mssql.secure_connection = Off

[Assertion]

[COM]

[mbstring]

[gd]

[exif]

[Tidy]

tidy.clean_output = Off

[soap]

soap.wsdl_cache_enabled=1

soap.wsdl_cache_dir="/tmp"

soap.wsdl_cache_ttl=86400

soap.wsdl_cache_limit = 5

[sysvshm]

[ldap]

ldap.max_links = -1

[mcrypt]

[dba]

[curl]

[свернуть]

Leo

#3
Пробовали локализовать проблему - найти кусок кода, который подвешивает скрипт?
Этот скрипт стоял на другой ОС и работал?

Сообщение объединено: 10 марта 2015, 14:37:09

Ну или профайлером посмотреть... куда что утекло...

lk1918

Благодарю за ссылки. Поставил профайлер, буду смотреть.
Еще один вопрос. Обнаружил в syslog:

Mar  6 04:09:01 localhost /USR/SBIN/CRON[12474]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -x /usr/lib/php5/sessionclean ] && [ -d /var/lib/php5 ] && /usr/lib/php5/sessionclean /var/lib/php5 $(/usr/lib/php5/maxlifetime))
Mar  6 04:17:01 localhost /USR/SBIN/CRON[12550]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)

И так повторяется периодически. Я правильно понимаю, что в кроне висят задачи по убиванию сессий?
И не может ли это влиять на подобную проблему?