C程序 杀死指定名称的进程

int kill_process_by_name(char *processname)
{
    FILE *pstr;
    char cmd[128],buff[512],*p;
    pid_t pID;
    int pidnum;

    int ret= -1;
    memset(cmd,0,sizeof(cmd));
    sprintf(cmd, "ps -ef|grep %s ",processname);
    pstr=popen(cmd, "r");
    if(pstr==NULL)
    {
        return 1;
    }
    memset(buff,0,sizeof(buff));
    fgets(buff,512,pstr);
    p=strtok(buff, " ");
    p=strtok(NULL, " ");
	pclose(pstr);
    if(p==NULL)
    {
        return 1;
    }
    if(strlen(p)==0)
    {
        return 1;
    }
    if((pidnum=atoi(p))==0)
    {
        return 1;
    }
    printf("pidnum: %d\n",pidnum);
    pID=(pid_t)pidnum;
    //ret=kill(pID,0);
	ret=kill(pID, 9);
    printf("ret= %d \n",ret);
    if(0==ret)
        printf("process: %s kill!\n", processname);
    else
        printf("process: %s not kill!\n",processname);
    return 0;
}

你可能感兴趣的:(Linux命令)