[C/C++]获得进程号PID、进程名

持续完善中,欢迎留言补充


直接上代码
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;
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值