memcleaner.cpp

来自「linux下的垃圾收集」· C++ 代码 · 共 49 行

CPP
49
字号
#include <iostream>
#include <assert.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <pwd.h>
#include <sys/wait.h>

int main (int argc,char* argv[]) 
{
	//printf("we have %d param, they are %s %s %s %s.\n", argc, argv[0], argv[1], argv[2], argv[3]);	
	if (argc != 4)
	{
		printf("Memory system's cleaner cannot run.\r\n");
		exit(1);
	}
	// the first will be my program name
	// second will be the main process id
	// third will be queue number
	// forth will be the msg file path
	setpgrp();
	int nExit = 0;
	int nMainPid = atoi(argv[1]);
	int nMsgQueue = atoi(argv[2]);
	while(!nExit)
	{
		//向被监视进程发送0信号,以探测其生存状态
		int nRtn = kill(nMainPid , 0);
		
		if (nRtn != 0)
		{//如果被监视进程已经不存在,则试图删除消息队列和文件标识,并退出
			msgctl( nMsgQueue, IPC_RMID, NULL ); // delete the message queue
			unlink( argv[3] );
			nExit = 1;
		}
		else
		{
			sleep(1);
		}
		
	}
	
	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?