Check linux process dead
from http://q.hatena.ne.jp/1162811274
or
int CheckProcessExist (char *processName)
{
int i=0;
int result =1;
FILE *fp = NULL;
for(i=0; i<3; i++)
{
fp = NULL;
char buf[10240];
memset(buf,'\0',sizeof(buf));
char cmdline[1024];
memset(cmdline,'\0',sizeof(cmdline));
sprintf (cmdline, "ps -ax | grep %s > /var/log/idt/CheckProcessExist.txt;", processName);
system(cmdline);
fp = fopen("/var/log/idt/CheckProcessExist.txt","r");
if(fp==NULL)
{
LogTo("command line fail as follows", "/var/log/idt/StopKeepalived.log",user);
LogTo(cmdline, "/var/log/idt/StopKeepalived.log",user);
continue;
}
while((fgets(buf,sizeof(buf)-1,fp))!=NULL)
{
if(strstr(buf,"bash: ps:") != NULL)
{
SendExecuteFailSnmptrap(cmdline);
LogTo("monitor_server down as ps not found", "/var/log/idt/StopKeepalived.log",user);
LogTo(cmdline, "/var/log/idt/StopKeepalived.log",user);
pclose(fp);
return 1;
} else if(strstr(buf,"ps -ax") != NULL)
{
} else if(strstr(buf,"grep") != NULL)
{
} else if(strstr(buf,processName) != NULL)
{
return 0;
}
memset(buf,'\0',sizeof(buf));
}
if(fp != NULL)
{
fclose(fp);
}
else
{
LogTo("FP is null", "/var/log/idt/StopKeepalived.log",user);
}
LogTo("CheckProcessExist return 1", "/var/log/idt/StopKeepalived.log",user);
sleep(3);
}
return result;
}
生きていると判別できます。
なお、あまり知られていませんが、Linux を含めた大抵の OS では、まれにプロセスが生きていても ps 等に表示されない(proc の下に出ない)ことがありますので、確実に死んでいることを判別する場合には、以下のサンプルコードのように2回チェックするとよいです。
or
int CheckProcessExist (char *processName)
{
int i=0;
int result =1;
FILE *fp = NULL;
for(i=0; i<3; i++)
{
fp = NULL;
char buf[10240];
memset(buf,'\0',sizeof(buf));
char cmdline[1024];
memset(cmdline,'\0',sizeof(cmdline));
sprintf (cmdline, "ps -ax | grep %s > /var/log/idt/CheckProcessExist.txt;", processName);
system(cmdline);
fp = fopen("/var/log/idt/CheckProcessExist.txt","r");
if(fp==NULL)
{
LogTo("command line fail as follows", "/var/log/idt/StopKeepalived.log",user);
LogTo(cmdline, "/var/log/idt/StopKeepalived.log",user);
continue;
}
while((fgets(buf,sizeof(buf)-1,fp))!=NULL)
{
if(strstr(buf,"bash: ps:") != NULL)
{
SendExecuteFailSnmptrap(cmdline);
LogTo("monitor_server down as ps not found", "/var/log/idt/StopKeepalived.log",user);
LogTo(cmdline, "/var/log/idt/StopKeepalived.log",user);
pclose(fp);
return 1;
} else if(strstr(buf,"ps -ax") != NULL)
{
} else if(strstr(buf,"grep") != NULL)
{
} else if(strstr(buf,processName) != NULL)
{
return 0;
}
memset(buf,'\0',sizeof(buf));
}
if(fp != NULL)
{
fclose(fp);
}
else
{
LogTo("FP is null", "/var/log/idt/StopKeepalived.log",user);
}
LogTo("CheckProcessExist return 1", "/var/log/idt/StopKeepalived.log",user);
sleep(3);
}
return result;
}
留言
張貼留言