当前位置: 技术问答>linux和unix
进来看看,怎样监控一个程序开始运行的消息?
来源: 互联网 发布时间:2015-08-07
本文导语: 需要些一个程序A,当他运行时可以监控某个程序B的运行,例如A运行后,这时运行B,则A能够以所能达到的最快的速度知道B的运行。 这该怎么做呢?那位能够给一段样例程序。谢谢? | ...
需要些一个程序A,当他运行时可以监控某个程序B的运行,例如A运行后,这时运行B,则A能够以所能达到的最快的速度知道B的运行。
这该怎么做呢?那位能够给一段样例程序。谢谢?
这该怎么做呢?那位能够给一段样例程序。谢谢?
|
让A不停的检测进程中有没有B就行了
long* find_pid_by_name(char* pidName)
{
DIR *dir;
struct dirent *next;
long* pidList=NULL;
int i=0;
dir = opendir("/proc");
if (!dir)
{
fprintf(stderr, "Cannot open /procn");
return NULL;
}
while ((next = readdir(dir)) != NULL)
{
FILE *status;
char filename[READ_BUF_SIZE];
char buffer[READ_BUF_SIZE];
char name[READ_BUF_SIZE];
/* Must skip ".." since that is outside /proc */
if (strcmp(next->d_name, "..") == 0)
continue;
/* If it isn't a number, we don't want it */
if (!isdigit(*next->d_name))
continue;
sprintf(filename, "/proc/%s/status", next->d_name);
if (! (status = fopen(filename, "r")) )
{
continue;
}
/* Read first line in /proc/?pid?/status */
if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL)
{
fclose(status);
continue;
}
fclose(status);
/* Buffer should contain a string like "Name: binary_name" */
sscanf(buffer, "%*s %s", name);
if (strcmp(name, pidName) == 0)
{
pidList=realloc( pidList, sizeof(long) * (i+2));
pidList[i++]=strtol(next->d_name, NULL, 0);
}
}
if (pidList)
{
pidList[i]=0;
}
else
{
pidList=realloc( pidList, sizeof(long));
pidList[0]=-1;
}
closedir(dir);
return pidList;
}
long* find_pid_by_name(char* pidName)
{
DIR *dir;
struct dirent *next;
long* pidList=NULL;
int i=0;
dir = opendir("/proc");
if (!dir)
{
fprintf(stderr, "Cannot open /procn");
return NULL;
}
while ((next = readdir(dir)) != NULL)
{
FILE *status;
char filename[READ_BUF_SIZE];
char buffer[READ_BUF_SIZE];
char name[READ_BUF_SIZE];
/* Must skip ".." since that is outside /proc */
if (strcmp(next->d_name, "..") == 0)
continue;
/* If it isn't a number, we don't want it */
if (!isdigit(*next->d_name))
continue;
sprintf(filename, "/proc/%s/status", next->d_name);
if (! (status = fopen(filename, "r")) )
{
continue;
}
/* Read first line in /proc/?pid?/status */
if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL)
{
fclose(status);
continue;
}
fclose(status);
/* Buffer should contain a string like "Name: binary_name" */
sscanf(buffer, "%*s %s", name);
if (strcmp(name, pidName) == 0)
{
pidList=realloc( pidList, sizeof(long) * (i+2));
pidList[i++]=strtol(next->d_name, NULL, 0);
}
}
if (pidList)
{
pidList[i]=0;
}
else
{
pidList=realloc( pidList, sizeof(long));
pidList[0]=-1;
}
closedir(dir);
return pidList;
}
|
用信号试试