看windows api的时候,作为练习,编写了个删除进程的程序。觉得里面知识点挺多的,所以贴上来当个笔记用。当然难免有错误,欢迎指教 ^^
其中也用到了篇文章里面说到的调整权限的函数,于是就直接从关机程序里面copy过来了。下面是程序,关键地方给了注释。
看windows api的时候,作为练习,编写了个删除进程的程序。觉得里面知识点挺多的,所以贴上来当个笔记用。当然难免有错误,欢迎指教 ^^
其中也用到了上篇文章里面说到的调整权限的函数,于是就直接从关机程序里面copy过来了。下面是程序,关键地方给了注释。
#include<stdio.h>
#include<windows.h>
#include<tlhelp32.h>
void listprocess() //列出进程名称及id
{
handle hprocesssnap=null;
processentry32 pe32={0}; //存放进程信息的结构体
hprocesssnap=createtoolhelp32snapshot(th32cs_snapprocess,0); //创建系统所有进程的快照
if(hprocesssnap==invalid_handle_value)
{
printf("createtoolhelp32snapshot failed: %d\n",getlasterror());
return;
}
pe32.dwsize=sizeof(processentry32);
printf("processname processid\n");
if(process32first(hprocesssnap,&pe32)) //指向第一个进程,并将其放入processentry32结构体中
{
char c[5];
do
{
itoa(pe32.th32processid,c,10);
printf("%-30s%d\n",pe32.szexefile,pe32.th32processid); //szexefile为进程的可执行文件名称
}
while(process32next(hprocesssnap,&pe32));
}
else
{
printf("process32first() failed:%d\n",getlasterror());
}
closehandle(hprocesssnap);
return;
}
bool enableprivilege() //获取系统权限
{
handle hprocess = null;
handle htoken = null;
luid uid = {0};
token_privileges sttoken_privileges = {0};
hprocess = getcurrentprocess(); //获取当前应用程序进程句柄
if(!openprocesstoken(hprocess,token_adjust_privileges,&htoken)) //打开当前进程的访问令牌句柄
//(openprocesstoken函数调用失败返回值为零)
return false;
if(!lookupprivilegevalue(null,se_shutdown_name,&uid)) //获取权限名称为"seshutdownprivilege"的luid
//lookupprivilegevalue函数调用失败返回值为零
return false;
sttoken_privileges.privilegecount = 1; //欲调整的权限个数
sttoken_privileges.privileges[0].luid = uid; //权限的luid
sttoken_privileges.privileges[0].attributes = se_privilege_enabled; //权限的属性,
//se_privilege_enabled为使能该权限
//调整访问令牌里的指定权限(adjusttokenprivileges函数调用失败返回值为零)
if(!adjusttokenprivileges(htoken,false,&sttoken_privileges,sizeof sttoken_privileges,null,null))
return false;
if(getlasterror() != error_success) //查看权限是否调整成功
return false;
closehandle(htoken);
return true;
}
bool killprocess(dword id)
{
handle hprocess=null,hprocesstoken=null;
bool iskilled=false,bret=false;
enableprivilege(); //调整权限
printf("enable privilege ok!\n");
if((hprocess=openprocess(process_all_access,false,id))==null) //打开进程获得句柄
{
printf("open process %d failed: %d\n",id,getlasterror());
return false;
}
if(!terminateprocess(hprocess,1)) //终结进程
{
printf("terminateprocess failed: %d\n",getlasterror());
return false;
}
iskilled=true;
if(hprocesstoken!=null)
closehandle(hprocesstoken);
if(hprocess!=null)
closehandle(hprocess);
return iskilled;
}
void main()
{
int id=0;
listprocess();
while(1)
{
printf("选择要删除的进程id:");
scanf("%d",&id);
if(killprocess(id)==true)
{
system("cls");
listprocess();
}
else
printf("failed!!");
}
}
以上就是一个删除进程的小程序详细介绍的详细内容。