- 论坛徽章:
- 0
|
有没有系统调用可以判断某进程是否存在?
给一个我们用的例子,其实就是仿照busybox里面的code改写。
- pid_t* find_pid_by_name( char* pidName, int *count)
- {
- DIR *dir;
- struct dirent *next;
- pid_t *pidList;
- int i=0,n=0,j=0;
-
- dir = opendir("/proc");
- if (!dir)
- {
- printf("find_pid_by_name: Cannot open /proc");
- exit(1);
- }
- pidList = malloc(sizeof(*pidList)*5);
- 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);
- sprintf(filename, "/proc/%s/cmdline", next->;d_name);
- if (! (status = fopen(filename, "r")) ) {
- continue;
- }
- /*if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL) {
- fclose(status);
- continue;
- } */
- n=fread(buffer, 1,READ_BUF_SIZE-1, status);
- if ( n <= 0)
- {
- fclose(status);
- continue;
- }
-
- fclose(status);
- // Buffer should contain the command string
- if ( n>;=4 )
- {
- if ( bstrncmp(buffer, pidName,n-1) == 0 )
- {
- pidList[i]=strtol(next->;d_name, NULL, 0);
- printf("find_pid_by_name(): PID(%d) match\n",strtol(next->;d_name, NULL, 0));
- i++;
- }
- }
- }
- closedir(dir) ;
- *count = i;
- printf("find_pid_by_name(): %d\n", *count);
- return pidList;
- }
复制代码 |
|