C程序监测进程是否存在

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_41666796/article/details/86520015
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 

int main()
{
    FILE *ptr = NULL;
    char cmd[128] = "ps -ef | grep mp_client0 | grep -v grep | wc -l";
    int status = 0;
    char buf[150];
    int count;

    if((ptr = popen(cmd, "r"))==NULL)
    {   
        printf("popen err\n");  
    }   
    memset(buf, 0, sizeof(buf));

    if((fgets(buf, sizeof(buf),ptr))!= NULL)//获取进程和子进程的总数
    {   
        count = atoi(buf);
        if(count <= 0)//当进程数小于等于0时,说明进程不存在
        {   
            printf("not exist \n");
        }else{

            printf("exist \n");
        }   

    }   

}

展开阅读全文

如何查一个进程是否存在

02-21

[code=C/C++]#include rn#include rn#include //Additional Dependencies下增shlwapi.librn#include rnusing namespace std;rnrn//查一个进程是否存在?rnbool CheckAProcessExit(const char * exeName)rnrn if (NULL == exeName)rn rn return false;rn rnrn HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);rn if (NULL == snapshot)rn rn return false;rn rnrn SHFILEINFO shSmall;rn PROCESSENTRY32 processinfo;rn processinfo.dwSize = sizeof(processinfo);rnrn BOOL status = Process32First(snapshot, &processinfo);rn while (status)rn rn ZeroMemory(&shSmall, sizeof(shSmall));rn SHGetFileInfo(processinfo.szExeFile, 0, &shSmall, sizeof(shSmall), SHGFI_ICON|SHGFI_SMALLICON);rnrn if (!strcmp(processinfo.szExeFile, exeName)) //确保非Unicodern rn return true;rn rn status = Process32Next(snapshot, &processinfo);rn rnrn return false;rnrnrnint APIENTRY WinMain(HINSTANCE hInstance,rn HINSTANCE hPrevInstance,rn LPTSTR lpCmdLine,rn int nCmdShow)rnrn Sleep(100);rn while (CheckAProcessExit("UpdateUI.exe"))rn rn Sleep(300);rn rnrn char path[MAX_PATH] = 0;rn GetCurrentDirectory(MAX_PATH, path);rn string strSrcPath = path;rnrn //这两个文件都存在,则拷贝到一个临时文件夹中,再进行安装rn if ((PathFileExists("Setup.exe")) && (PathFileExists("data.bin")))rn rn //查临时文件夹rn string strDesPath = strSrcPath;rn strDesPath.append("\\sys");rn if (strDesPath.size() < MAX_PATH)rn rn BOOL bRet = FALSE;rn if (!PathFileExists(strDesPath.c_str()))rn rn bRet = CreateDirectory(strDesPath.c_str(), NULL);rn if (!bRet)rn rn return 2;rn rn rn //拷贝到临时文件夹rn string strSrcFile1 = strSrcPath;rn strSrcFile1.append("\\Setup.exe");rn string strDesFile1 = strDesPath;rn strDesFile1.append("\\Setup.exe");rn string strSrcFile2 = strSrcPath;rn strSrcFile2.append("\\data.bin");rn string strDesFile2 = strDesPath;rn strDesFile2.append("\\data.bin");rn bRet = CopyFile(strSrcFile1.c_str(), strDesFile1.c_str(), FALSE);rn if (!bRet)rn rn return 3;rn rn bRet = CopyFile(strSrcFile2.c_str(), strDesFile2.c_str(), FALSE);rn if (!bRet)rn rn return 4;rn rnrn //拷贝成功rn if (PathFileExists(strDesFile1.c_str()))rn rn ShellExecute(NULL, "open", strDesFile1.c_str(), NULL, NULL, SW_SHOWNORMAL);rn return 88;rn rn rn return 1;rn rnrn return 0;rn[/code]rn以上能查一个进程是否存在,但进程是动态增减的,不知此法是否有缺陷? 论坛

没有更多推荐了,返回首页