跨平台判断进程是否存在
2010-06-01 00:11
453 查看
根据进程名判断进程是否存在,并返回进程的PID。
#include <string> #include <algorithm> #include <functional> #include <map> #include <time.h> #include <vector> #include <sstream> #include <fstream> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #ifdef WIN32 #define PID DWORD #include <winsock2.h> #include <process.h> #pragma comment(lib, "Ws2_32.lib") #include <direct.h> #include "tlhelp32.h" #include "shellapi.h" #else #define PID p_id #include <unistd.h> #include <dirent.h> #include <stdlib.h> #include <sys/procfs.h> #include <unistd.h> #include <stropts.h> #include <fcntl.h> #include <signal.h> #endif /** * @brief processExist * * Detailed description. * @param[in] processName * @param[out] pid * @return bool */ inline bool processExist(std::string processName, PID& pid) { #ifdef WIN32 HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hProcessSnap == INVALID_HANDLE_VALUE) { return false; } PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); if(!Process32First(hProcessSnap, &pe32)) { CloseHandle(hProcessSnap); return false; } do { if(0 == strcmp(pe32.szExeFile, processName.c_str())) { pid = pe32.th32ProcessID; CloseHandle(hProcessSnap); return true; } }while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); #else if (-1 == isFileOrDir("/tmp/test.tmp")) { remove("/tmp/test.tmp"); } system(("ps -e|grep " + processName + "|awk '{print $1}' >> /tmp/test.tmp").c_str()); std::ifstream infile("/tmp/test.tmp"); remove("/tmp/test.tmp"); std::string pidStr; if (infile >> pidStr) { if(isNumber(pidStr)) { infile.close(); pid = static_cast<pid_t>(atoi(pidStr.c_str())); return true; } } infile.close(); #endif return false; }
相关文章推荐
- Linux下判断是否存在多个同名进程
- 判断进程是否存在的几种方法
- Shell实现判断进程是否存在并重新启动脚本分享
- C++ 判断进程是否存在
- VC判断指定进程是否存在IsExistProcess
- Shell实现判断进程是否存在并重新启动脚本
- linux判断进程或者cron是否存在shell
- C++ 判断进程是否存在
- DOS中判断进程是否存在的方法
- QTP的那些事--判断进程是否存在
- 判断某进程是否存在
- 在纯java中实现跨平台判断该进程是否已经启动
- Linux判断进程是否存在并启动该进程
- Linux C语言 如何判断该进程是否还存在
- C#判断进程是否存在并结束进程
- QTP中如何判断Excel进程是否存在?
- linux shell 判断进程是否存在
- python 判断一个进程是否存在
- C#判断进程是否存在并结束进程
- Linux Shell中判断进程是否存在的方法