根据进程名称杀掉进程
思路:
1、 遍历/proc文件夹下所有数字开头的文件夹,访问其status文件,读取Name那项的信息,如果跟要杀的进程名一致,则说明该文件夹名字就是进程PID。
2、通过signal发送SIGINT消息(模拟Ctrl+C)
3、如果进程还存在,发送SIGKILL消息
头文件代码:
#ifndef _My_KILL_Process_H #define _My_KILL_Process_H /* 尝试杀掉进程 0: 完成。使用SIGINT 杀掉进程 1:完成。使用SIGKILL 杀掉进程 -1: 无法打开/proc文件夹 -2: 找不到进程 -3: 杀进程失败 -4: 无法杀掉进程 //如果错误,可以获取错误字符串. //errStr */ int TryKillProcess(char* pname ,char *errStr); #endif // ! _My_KILL_Process_H
实现文件:
#include#include #include #include #include #include #include #include #include"myKillProcess.h" //根据进程名称获取PID 。 //如果失败返回-1,没找到返回0 static pid_t GetPidByName(const char *pName) { DIR *pdir = NULL; struct dirent *pde = NULL; FILE *pf = NULL; char buff[500]; pid_t pid; char szName[256]; // 遍历/proc目录下所有pid目录 pdir = opendir("/proc"); if (!pdir) { return -1; } while ((pde = readdir(pdir))) { if ((pde->d_name[0] < '0')|| (pde->d_name[0] > '9')) { continue; } // 读取 /proc/$pid/status文件 sprintf(buff, "/proc/%s/status", pde->d_name); pf = fopen(buff, "r"); if (pf) { fgets(buff,sizeof(buff),pf); fclose(pf); sscanf(buff,"%*s %s",szName); // 跳过Name:字段,获取进程名称 pid=atoi(pde->d_name); if(strcmp(szName,pName)==0) { closedir(pdir); return pid; } } } closedir(pdir); return 0; } /* 0: 完成。使用SIGINT 杀掉进程 1:完成。使用SIGKILL 杀掉进程 -1: 无法打开/proc文件夹 -2: 找不到进程 -3: 杀进程失败 -4: 无法杀掉进程 */ int TryKillProcess(char* pname ,char *errstr) { //第一步:查进程对应的PID pid_t mypid = GetPidByName(pname); if(mypid<0) { strcpy(errstr,"无法打开/proc文件夹\n"); return -1; } if(mypid==0){ sprintf(errstr, "找不到进程%s",pname); return -2; } //第二步:尝试用SIGINT方式杀进程 int err1 = kill(mypid,SIGINT); if(err1!=0){ sprintf(errstr, "杀进程失败[%s]",strerror(errno)); return -3; } //wait 10ms usleep(10000); mypid = GetPidByName(pname); if(mypid<0) { strcpy(errstr,"无法打开/proc文件夹\n"); return -1; } if(mypid==0){ strcpy(errstr,"成功通过SIGINT杀掉进程"); return 0; } //第三步:尝试用SIGKILL方式 err1 = kill(mypid,SIGKILL); if(err1!=0){ sprintf(errstr, "杀进程失败[%s]",strerror(errno)); return -3; } //wait 10ms usleep(10000); mypid = GetPidByName(pname); if(mypid<0) { strcpy(errstr,"无法打开/proc文件夹\n"); return -1; } if(mypid==0){ strcpy(errstr,"成功通过SIGKILL杀掉进程"); return 1; } sprintf(errstr, "无法杀掉进程[%s]",pname); return -4; }
测试文件:
#include#include"myKillProcess.h" int main(int argc, char **argv) { if(argc!=2) { perror("缺少要杀的进程名。\n"); return -1; } char errstr[256]={0}; int ret = TryKillProcess(argv[1],errstr); printf("结果:%s\n",errstr); return 0; }