linux 检测进程是否存在

1. 直接遍历/proc目录

  

int find_pid_by_name( char* pidname, pid_t *pidlist)
{
#define READ_BUF_SIZE 256

    DIR *dir;
    struct dirent *next;
    int i = 0;
 
    dir = opendir("/proc");

		if (!dir)
    {
    	printf("Cannot open /proc");
		}
     
    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;
        }
				
        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[i++] = strtol(next->d_name, NULL, 0);
        }
    }

	return i;
}

int is_cap_running()
{
	pid_t pid_list[128];

	if(find_pid_by_name("capSrv", pid_list) > 1)
	{
		printf("capSrv already run, pid:%u \n", 
				(pid_list[0] == getpid()) ? pid_list[1] : pid_list[0]);
		return 1;
	}
	else
	{
		return 0;
	}
}

  

 2. 调用pidof

char buf[256] = {0};
	int pos = 0;
	pid_t cur_pid = getpid();
	
	char *cmd = "pidof capSrv";
	FILE *file = popen(cmd, "r");


	while(fgets(buf, 256, file) != NULL)
	{
		printf("%s fgets: %s \n", cmd, buf);		
		if(isdigit(buf[0]))
		{
			pclose(file);
			
			if(sscanf(buf,"%u %u", &pid[0],pid[1]) == 2)
			{
				printf("capSrv already run, pid:%u \n", (pid[0] == cur_pid) ? pid[1] : pid[0]);
				return 1;
			}
			else
			{
				return 0;
			}
		}
	}

 3. ps 

posted on 2014-07-07 09:55  偏爱省略号  阅读(700)  评论(0编辑  收藏  举报

导航