持续完善中,欢迎留言补充
直接上代码
wtaskz.h
//
// wtaskz.h
// ftpz
//
// Created by 胖胖的ALEX on 2017/10/25.
//
#ifndef WZASKZ_H
#define WZASKZ_H
#include <string>
/* 执行cmd命令,打印内容保存到result
@cmd 命令行
@result 命令打印的内容
@pos 返回第几行数据,如果0返回所有,1返回第一行,以此类推
例子:下面打印结果,0返回所有,pos=1返回 Image Name: TIM.exe
Image Name: TIM.exe
PID: 3044
Session Name: Console
Session#: 2
Mem Usage: 171,088 K
*/
int execmd_z(char* cmd, char* result, int pos);
/* 获得进程号 */
int pid_z();
/* 通过进程名获得进程号,保存到pid
@imagename 映像名字(进程名),例如:qq.exe
@pid 进程号
例子:
char pid[100];
memset(pid, 0, sizeof(pid));
pidbyimagename_z("Tim.exe", pid);
std::cout << pid << std::endl;
*/
int pidbyimagename_z(char* imagename, char* pid);
/* 通过进程号获得进程名,保存到imagename
@pid 进程号
@imagename 映像名字(进程名),例如:qq.exe
例子:
char imagename[100];
memset(imagename, 0, sizeof(imagename));
imagenamebypid_z("3709", imagename);
std::cout << imagename << std::endl;
*/
int imagenamebypid_z(char* pid, char* imagename);
#endif // !WZASKZ_H
wtaskz.cpp
//
// wtaskz.cpp
// ftpz
//
// Created by 胖胖的ALEX on 2017/10/25.
//
#include "stdafx.h"
#include "wtaskz.h"
#include "stringz.h"
#include <iostream>
#include <fstream>
#include <process.h>
int execmd_z(char* cmd, char* result, int pos)
{
char buffer[128]; // 定义缓冲区
FILE* pipe = _popen(cmd, "r"); // 打开管道,并执行命令
if (!pipe)
return 0; // 返回0表示运行失败
int i = 1;
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe)) { // 将管道输出到result中
if (buffer[0] == '\n')
continue;
if (pos == 0) {
strcat(result, buffer);
}
else if (pos == i)
{
strcat(result, buffer);
break;
}
i++;
}
}
_pclose(pipe); // 关闭管道
return 1;
}
int pid_z()
{
return _getpid();
}
int pidbyimagename_z(char* imagename, char* pid)
{
char cmd[128];
memset(cmd, 0, sizeof(cmd));
std::sprintf(cmd, "%s%s%s", "tasklist /fi \"imagename eq ", imagename, "\" /fo list");
execmd_z(cmd, pid, 2);
char pch[128];
strcpy(pch, pid);
std::vector<char*> vec;
vec = split_z(pch, ":");
if (vec.size() == 0)
return 0;
memset(pid, 0, sizeof(pid));
strcpy(pid, vec[1]);
rtrim_n_z(pid);
std::cout << "++" << pid << std::endl;
return 1;
}
int imagenamebypid_z(char* pid, char* imagename)
{
char cmd[128];
memset(cmd, 0, sizeof(cmd));
std::sprintf(cmd, "%s%s%s", "tasklist /fi \"pid eq ", pid, "\" /fo list");
execmd_z(cmd, imagename, 1);
char pch[128];
strcpy(pch, imagename);
std::vector<char*> vec;
vec = split_z(pch, ":");
if (vec.size() == 0)
return 0;
memset(imagename, 0, sizeof(imagename));
strcpy(imagename, vec[1]);
//std::cout << "++" << pid << std::endl;
rtrim_n_z(imagename);
return 1;
}