-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessCounter.cpp
More file actions
68 lines (55 loc) · 1.6 KB
/
processCounter.cpp
File metadata and controls
68 lines (55 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include "processCounter.h"
#include <string.h>
#include <stdio.h>
int processCounter::counter()
{
std::string cmdTemplate = "ps -eaf | grep -v \"sh -c\" | awk '{print $8}' | grep -w %s$ | grep -c %s";
char cmd[256];
memset(cmd,0,sizeof(cmd));
sprintf(cmd,cmdTemplate.c_str(),this->processName.c_str(),this->processName.c_str());
FILE *f = popen(cmd,"r");
if(NULL == f)
{
std::cout<<"popen error"<<std::endl;
return 0;
}
int result = 0;
fscanf(f,"%d",&result);
if(pclose(f) == -1)
{
perror("pclose");
std::cout<<"pclose error"<<std::endl;
}
if(result > 0)
std::cout<<this->processName<<" is already running..."<<std::endl;
return result;
}
bool processCounter::killProcess()
{
if(counter() >= 1)
{
std::string queryCmd = "ps -eaf | grep -v \"sh -c\" | awk '{if($8~\"" + this->processName + "\"" +")print $2}'";
FILE *f1 = popen(queryCmd.c_str(),"r");
if(NULL == f1)
{
std::cout<<"popen error"<<std::endl;
return false;
}
int pid = 0;
fscanf(f1,"%d",&pid);
std::cout<<processName<<" pid = "<<pid<<std::endl;
std::string killCmd = "kill -9 " + std::to_string(pid);
FILE *f2 = popen(killCmd.c_str(),"r");
if(NULL == f2)
{
std::cout<<"popen error, killCmd error"<<std::endl;
return false;
}
}else
{
std::cout<<processName<<" is not running, no need to kill"<<std::endl;
return false;
}
return true;
}