利用信号监视进程存在

下面这个例程可以用于监视某个进程是否存在。

 

#include

#include

using namespace std;

 

int get_pid(string & managerName)

{

        string strCmd = "pidof "+managerName;

        FILE *pp;

        char buffer[10];

        pp = popen(strCmd.c_str(), "r");

        memset(buffer, 0x00, 10);

        fgets(buffer, 10, pp);

        pclose(pp);

        return atoi(buffer);

}

 

int main(int argc, char **argv) {

        int i;

        union sigval value;

        string mName="NotificationManager";

        int pid = get_pid(mName); //获取进程id

 

        value.sival_int = 0;

 

        while(1)

        {

                i = sigqueue(pid, 0, value); //return 0 表示成功,也即具有pid的进程存在;请注意:权限问题,如果当前进程无权限向目标进程发送信号也会失败

                if(i){

                        cout<<"the progress is not exist"<

                        pid=get_pid(mName); //尝试重现根据程序名获取pid

                }

                else

                        cout<<"the progress is OK"<

        }

        return 0;

}

你可能感兴趣的:(利用信号监视进程存在)