我用C ++编写了一个程序,用于将文件中的进程读入向量,然后逐行执行进程。
我想知道哪些进程正在运行,哪些进程没有在c ++中使用proc
感谢。
我的代码:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iterator>
#include <cstdlib>
using namespace std;
int main()
{ int i,j;
std::string line_;
std::vector<std::string> process;
ifstream file_("process.sh");
if(file_.is_open())
{
while(getline(file_,line_))
{
process.push_back(line_);
}
file_.close();
}
else{
std::cout<<"failed to open"<< "\n";
}
for (std::vector<string>::const_iterator i = process.begin(); i != process.end(); ++i)
{
std::cout << *i << ' ';
std::cout << "\n";
}
for (unsigned j=0; j<process.size(); ++j)
{
string system=("*process[j]");
std::string temp;
temp = process[j];
std::system(temp.c_str());
std::cout << " ";
}
std::cin.get();
return 0;
}
答案 0 :(得分:2)
在C中,我使用kill(pid_t pid, int sig)
向特定的pid发送空白信号(0),因此在返回此函数时检查它是否处于活动状态。
我不知道你是否在C ++中有类似的功能,但因为你也在使用linux,所以可能值得检查signals。
答案 1 :(得分:1)
取自http://proswdev.blogspot.jp/2012/02/get-process-id-by-name-in-linux-using-c.html
在执行流程之前,将流程名称传递给此函数。如果getProcIdByName()返回-1,则可以自由运行process_name。如果返回有效的pid,那么,什么也不做,或者从你的软件中杀死并运行它,取决于你的需求。
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int getProcIdByName(string procName)
{
int pid = -1;
// Open the /proc directory
DIR *dp = opendir("/proc");
if (dp != NULL)
{
// Enumerate all entries in directory until process found
struct dirent *dirp;
while (pid < 0 && (dirp = readdir(dp)))
{
// Skip non-numeric entries
int id = atoi(dirp->d_name);
if (id > 0)
{
// Read contents of virtual /proc/{pid}/cmdline file
string cmdPath = string("/proc/") + dirp->d_name + "/cmdline";
ifstream cmdFile(cmdPath.c_str());
string cmdLine;
getline(cmdFile, cmdLine);
if (!cmdLine.empty())
{
// Keep first cmdline item which contains the program path
size_t pos = cmdLine.find('\0');
if (pos != string::npos)
cmdLine = cmdLine.substr(0, pos);
// Keep program name only, removing the path
pos = cmdLine.rfind('/');
if (pos != string::npos)
cmdLine = cmdLine.substr(pos + 1);
// Compare against requested process name
if (procName == cmdLine)
pid = id;
}
}
}
}
closedir(dp);
return pid;
}
int main(int argc, char* argv[])
{
// Fancy command line processing skipped for brevity
int pid = getProcIdByName(argv[1]);
cout << "pid: " << pid << endl;
return 0;
}