修改生产者和消费者都退出后,共享内存未删除的问题

生产者消费者注册信号处理函数,退出时检查如果没有其它进程使用共享内存,将共享内存删除
This commit is contained in:
guo_peixu
2022-06-30 15:16:08 +08:00
parent 89899d2d0a
commit 8267c9712e
6 changed files with 102 additions and 21 deletions

View File

@@ -24,7 +24,6 @@
#define CONSUMER_CARE_PID_SPEC 1
#define CONSUMER_CARE_PID_MAX_LEN 128
int g_cur_tty_fd = -1;
struct log_file_list{
char log_file_pre[MESA_SHM_LOG_PATH_LEN];
@@ -44,6 +43,10 @@ struct care_pid_list g_care_pid_list;
int g_output_mode = CONSUMER_OUTPUT_MODE_FILE;
int g_care_pid = CONSUMER_CARE_PID_ALL;
int *g_status = NULL;
int g_cur_tty_fd = -1;
struct MESA_shm_overview *g_shm_overview = NULL;
int g_shm_overview_id = -1;
void init_ring_queue_head_arrray(struct MESA_shm_overview *ovw, struct MESA_shm_queue_head **ring_queue_head)
{
@@ -514,12 +517,33 @@ error:
}
void signal_handler_exit(int signum)
{
if(g_status == NULL){
exit(0);
struct shmid_ds buf;
if(g_status != NULL){
*g_status = MESA_CONSUMER_NOT_RUNNING;
}
*g_status = MESA_CONSUMER_NOT_RUNNING;
if(g_shm_overview == NULL || g_shm_overview_id == -1){
goto out;
}
if(shmctl(g_shm_overview_id, IPC_STAT, &buf) == -1){
goto out;
}
if(buf.shm_nattch <= 1){
/*
This is the last process to use this shared memory,
we need to unlink the shared memory before the process exit
*/
MESA_shm_unlink(g_shm_overview, g_shm_overview_id);
}
out:
exit(0);
}
/*
if we use shmctl function and IPC_RMID parameter,
the shared memory will actually be destroyed only after the last process detaches it,
but no more attaches for the shared memory identified by the shmid parameter are allowed,
producer process and consumer process start at an indeterminate time,
so we have to use IPC_RMID parameter to unlink the shared memory when all processes exit
*/
void register_sginal_handler()
{
signal(SIGKILL, signal_handler_exit);
@@ -564,20 +588,20 @@ int main(int argc, char **argv)
}
int i = 0;
int ret = 0;
struct MESA_shm_overview *shm_overview = NULL;
struct MESA_shm_overview *tmp_ovw = NULL;
struct MESA_shm_queue_head *ring_queue_head[MESA_SHM_RING_QUEUE_NUM] = {NULL};
INIT_LIST_HEAD(&g_log_file_list.list);
ret = MESA_shm_alloc_overview(&shm_overview, &g_status);
ret = MESA_shm_alloc_overview(&g_shm_overview, &g_shm_overview_id, &g_status);
if(ret < 0){
return 0;
}
*g_status = MESA_CONSUMER_RUNNING;
register_sginal_handler();
init_ring_queue_head_arrray(shm_overview, ring_queue_head);
init_ring_queue_head_arrray(g_shm_overview, ring_queue_head);
while(1){
for(i = 0; i< MESA_SHM_RING_QUEUE_NUM; i++){
tmp_ovw = shm_overview + i;
tmp_ovw = g_shm_overview + i;
if(tmp_ovw->shmid == -1){
break;
}