通过进程名和进程号杀死相应进程

在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;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值