- 论坛徽章:
- 1
|
如何检测进程是否存在?
- Andrew Gierth <andrew@erlenstar.demon.co.uk>;
- 一种办法是读取/proc接口提供的信息
- --------------------------------------------------------------------------
- /* gcc -Wall -O3 -o getpid getpid.c */
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <sys/types.h>;
- #include <sys/stat.h>;
- #include <sys/procfs.h>;
- #include <unistd.h>;
- #include <stropts.h>;
- #include <dirent.h>;
- #include <fcntl.h>;
- static pid_t getpidbyname ( char * name, pid_t skipit )
- {
- DIR * dirHandle; /* 目录句柄 */
- struct dirent * dirEntry; /* 单个目录项 */
- prpsinfo_t prp;
- int fd;
- pid_t pid = -1;
- if ( ( dirHandle = opendir( "/proc" ) ) == NULL )
- {
- return( -1 );
- }
- chdir( "/proc" ); /* 下面使用相对路径打开文件,所以必须进入/proc */
- while ( ( dirEntry = readdir( dirHandle ) ) != NULL )
- {
- if ( dirEntry->;d_name[0] != '.' )
- {
- /* fprintf( stderr, "%s\n", dirEntry->;d_name ); */
- if ( ( fd = open( dirEntry->;d_name, O_RDONLY ) ) != -1 )
- {
- if ( ioctl( fd, PIOCPSINFO, &prp ) != -1 )
- {
- /* fprintf( stderr, "%s\n", prp.pr_fname ); */
- if ( !strcmp( prp.pr_fname, name ) ) /* 这里是相对路径,而且
- 不带参数 */
- {
- pid = ( pid_t )atoi( dirEntry->;d_name );
- if ( skipit != -1 && pid == skipit ) /* -1做为无效pid对
- 待 */
- {
- pid = -1;
- }
- else /* 找到匹配 */
- {
- close( fd );
- break; /* 跳出while循环 */
- }
- }
- }
- close( fd );
- }
- }
- } /* end of while */
- closedir( dirHandle );
- return( pid );
- } /* end of getpidbyname */
- static void usage ( char * arg )
- {
- fprintf( stderr, " Usage: %s <proc_name>;\n", arg );
- exit( EXIT_FAILURE );
- } /* end of usage */
- int main ( int argc, char * argv[] )
- {
- pid_t pid;
- if ( argc != 2 )
- {
- usage( argv[0] );
- }
- pid = getpidbyname( argv[1], -1 );
- if ( pid != -1 )
- {
- fprintf( stderr, "[ %s ] is: <%u>;\n", argv[1], ( unsigned int )pid );
- exit( EXIT_SUCCESS );
- }
- exit( EXIT_FAILURE );
- } /* end of main */
- --------------------------------------------------------------------------
- 这种技术要求运行者拥有root权限,否则无法有效获取非自己拥有的进程PID。注意
- 下面的演示
- # ps -f -p 223
- UID PID PPID C STIME TTY TIME CMD
- root 223 1 0 3月 09 ? 0:00 /usr/sbin/vold
- # ./getpid /usr/sbin/vold <-- 这个用法无法找到匹配
- # ./getpid vold <-- 只能匹配相对路径
- [ vold ] is: <223>;
- 当然你可以自己修改、增强程序,使之匹配各种命令行指定,我就不替你做了。上述
- 程序在32-bit kernel的Solaris 2.6和64-bit kernel的Solaris 7上均测试通过。
复制代码 |
|