您的位置:首页 > 其它

跨平台判断进程是否存在

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;   
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: