Chinaunix首页 | 论坛 | 博客
  • 博客访问: 854885
  • 博文数量: 102
  • 博客积分: 7086
  • 博客等级: 少将
  • 技术积分: 2245
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-18 11:01
文章分类

全部博文(102)

文章存档

2012年(2)

2011年(1)

2010年(21)

2009年(31)

2008年(47)

我的朋友

分类: LINUX

2009-05-14 18:47:06

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 */
阅读(2992) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~