Project Home
Project Home
Trackers
Trackers
Documents
Documents
Wiki
Wiki
Discussion Forums
Discussions
Project Information
Project Info
Forum Topic - How to get the PID by process name.: (1 Item)
   
How to get the PID by process name.  
How to get the PID by process name, if you issue "#pidin -p processname", it's a piece of cake. But if you want to 
imeplement the function by C code, as below:

pid_t GetProcessPid(const char *process ){
	DIR *dirp;
	struct dirent *dire;
	char buffer[32];
	int fd=0, status;
	pid_t pid;
	struct dinfo_s {
		procfs_debuginfo info;
		char pathbuffer[PATH_MAX];
	} dinfo;

//	WriteDebugInfo("GetProcessId(%s)\r\n", process) ;

	if ((dirp = opendir( "/proc" )) == NULL)
	{
		closedir( dirp );
		printf( "Could not open '/proc'\n" );
		return -1;
	}

	while (1)
	{
		if ((dire = readdir( dirp )) == NULL) break;
		if (isdigit( dire->d_name[0] ))
		{
			pid = strtoul( dire->d_name, NULL, 0 );
			sprintf( buffer, "/proc/%d/as", pid );
			if (fd>0) close( fd );
			fd = open( buffer, O_RDONLY ) ;
			if (fd>0)
			{
				status = devctl( fd, DCMD_PROC_MAPDEBUG_BASE, &dinfo, sizeof(dinfo), NULL ) ;
				if (status == EOK)
				{

//					WriteDebugInfo("[%s]\r\n", basename(dinfo.info.path)) ;

					if (!strcmp(process, basename(dinfo.info.path)))
					{
						if (fd>0) close( fd );
						closedir( dirp );
						//printf("[%s]\r\n", basename(dinfo.info.path)) ;
						return pid;
					}
				}
				if (fd>0) close( fd );
			}
		}
	}
	if (fd>0) close( fd );
	closedir( dirp );
	return 0;
}