在linux系统中,我们可以通过在/proc目录下查看所有的运行的进程。在/proc的目录下,每个进程对应一个文件夹,并且进程号与文件名相对应。在进程文件夹内有一个status文件,其第一行对应的对应的就是进程名。我们由此可以通过进程名来获取相应的进程号。
通过进程名获取进程号
#include<dirent.h>
#include<stdio.h>
#define FILE_NAME_SIZE 256;
#define BUFF_SIZE 512;
#define OK 0UL;
#define ERR 1UL;
ULONG find_pid_by_name(int *pId, char *pName)
{
if(pId == NULL || pName == NULL)
return ERR;
DIR *dir;
struct dirent *dirp;
FILE *fp;
char file_name[FILE_NAME_SIZE];
char buf[BUFF_SIZE];
dir = opendir("/proc");
if(NULL != dir)
{
while((dirp = readdir(dir)) != NULL)
{
if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0 || dirp->d_type != DT_DIR)
continue;
sprintf(file_name, "/proc/%s/status", dirp->d_name);
fp = fopen(file_name, "r");
if(fp != NULL)
{
if(fget(buf, BUFF_SIZE-1, fp) == NULL)
{
fclose(fp);
continue;
}
sscanf(buf, "%*s%s", file_name);
if(!strcmp(pName, file_name))
{
//寻找到匹配进程名
fclose(fp);
*pId = atoi(dirp->d_name);
return OK;
}
}
}
closedir(dir);
}
//为查找到相应的进程名,查找失败
printf("can't find the pid by %s \r\n", pName);
return ERR;
}
通过进程号是杀死进程
我们可以通过kill函数传入相应的进程号来杀死相应的进程。
ULONG kill_process_by_id(int pid){
int status = kill(pid, SIGTERM);
if(status == -1){
printf("kill %d failed \r\n", pid);
return ERR;
}
wait(&status);
if(WIFSIGNALED(status)){
printf("child process receive signal %d\r\n", WTERMSIG(status));
return ERR;
}
return OK;
}
通过进场名杀死进程
通过调用上述的2个函数,我们可以通过进程名来对进程进行杀死
ULONG kill_process_by_name(char *task_name){
int id = -1;
int pid = &id;
ULONG ulRet;
if(task_name == NULL)
return ERR;
ulRet = find_pid_by_name(pid, task_name);
if(ulRet)
return ERR;
if(*pid == -1)
return ERR;
if(kill_process_by_id(*pid))
return ERR;
return OK;
}