static pid_t getpidbyname (char *name)
{
DIR *dirHandle; /* 目录句柄 */
struct dirent *dirEntry; /* 单个目录项 */
psinfo_t prp;
pid_t pid = -1;
char strPathName[100];
FILE *fp;
memset(strPathName, 0, 100);
if( ( dirHandle = opendir( "/proc" ) ) == NULL )
{
return( -1 );
}
chdir( "/proc" );
/* 下面使用相对路径打开文件,所以必须进入/proc */
while( ( dirEntry = readdir( dirHandle ) ) != NULL )
{
if( dirEntry->;d_name[0] != '.' && strcmp(dirEntry->;d_name,"sys") != 0)
{
/* 拼加路径 */
sprintf(strPathName, "./%s/%s", dirEntry->;d_name, "psinfo");
/* 读取文件 */
if( ( fp = fopen( strPathName, "rb" ) ) == NULL )
{
printf("打开文件[%s]失败!\n", strPathName);
break;
}
/* 读取数据 */
if(fread(&prp, sizeof(psinfo_t), 1, fp) == -1)
{
printf("文件读取失败!\n");
fclose(fp);
break;
}
if ( strcmp( prp.pr_fname, name) == 0 )
{
pid = ( pid_t )atoi( dirEntry->;d_name );
break;
}
fclose( fp );
}
} /* end of while */
closedir( dirHandle );
return( pid );
} /* end of getpidbyname */
阅读(3028) | 评论(0) | 转发(0) |