How to separate and remove shared memory between two processes in PHP?

I developed a way to do asynchronous tasks with PHP, and it works very well, so far.

The logic is based on 3 extensions of PCNTL , POSIX e Semaphore .

In order to have full control over the main process and the child process, I have to share the status of the task and the PID between them. These 2 variables are shared using shm_attach , fork uses pcntl_fork .

The problem described in the title of these questions is related to the status of the task and the PID between them. The two variables are separated using the shm_attach method because there is no shared memory available for sharing.

I use it for 2 minutes: In the constructor to create shared memory

<?php //... final public function __construct() { self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE); $this->var_key_pid = $this->alocatesharedMemory(getmypid(), 112112105100); //112112105100; $this->var_key_status = $this->alocatesharedMemory('PENDING', 11511697116117115); //11511697116117115; } 

And by the run method after formatting the process

 <?php final public function run($parameters) { //... } else { //Frok process ignore_user_abort(); //I dont know why but must be set again. $sid = posix_setsid(); self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE); 

NOTE. The code is a bit extended, and I introduced it to the point https://gist.github.com/LeonanCarvalho/62c6fe0b62db8a478f502f84c5734c83

I think I am doing something wrong, because although I use shm_detach and shm_remove the process sometimes returns a PHP error Warning: "shm_attach" failed for the key. Lack of free space on the device when I try to connect a new shared memory.

This is because some shared memory is disconnected and not deleted from the shared memory partitions; its result is the ipcs -m command:

ipcs -m result

Tasks are completed for several months before starting to do this, so one way to get around this problem is to delete all shared memory identifiers with

 ipcrm --all=shm 

But I think that it is growing quietly, and it will certainly happen again.

How to prevent this?

+5
source share
1 answer

I think that a process may be a memory leak due to created and not destroyed objects inside the process memory. one of the ways you can analyze this is to analyze the memory usage in the process and what requests are sent, which can cause this problem, if you can reproduce the creation and the memory leak, then it should be possible to figure out a way to delete the created objects. this may be because cursors remain open among other factors. Have you considered using RabbitMQ for async PHP tasks?

+1
source

Source: https://habr.com/ru/post/1273358/


All Articles