Pidof从一个后台脚本到另一个后台进程



我写了一个c++程序来检查进程是否正在运行。这个进程在后台独立启动。当我在前台运行它时,我的程序工作得很好,但当我对它进行时间调度时,它不工作。

int PID=  ReadCommanOutput("pidof /root/test/testProg1"); /// also tested with pidof -m

我在/etc/cron.中创建了一个脚本D/myscript按如下方式安排时间:-

45 15 * * * root /root/ProgramMonitor/./testBkg > /root/ProgramMonitor/OutPut.txt

这是什么原因呢?

     string ReadCommanOutput(string command)
      {
          string output="";
          int its=system((command+" > /root/ProgramMonitor/macinfo.txt").c_str());
          if(its==0)
           {
                  ifstream reader1("/root/ProgramMonitor/macinfo.txt",fstream::in);
                  if(!reader1.fail())
                     {
                      while(!reader1.eof())
                       {
                          string line;
                          getline(reader1,line);
                          if(reader1.fail())// for last read
                          break;
                          if(!line.empty())
                          {
                             stringstream ss(line.c_str());
                             ss>>output;
                             cout<<command<<" output = ["<<output<<"]"<<endl;
                              break;
                         }
                }
                reader1.close();
                remove("/root/ProgramMonitor/macinfo.txt");
               }
             else
                cout<<"/root/ProgramMonitor/macinfo.txt not found !"<<endl;
         }
         else
           cout<<"ERROR: code = "<<its<<endl;
      return output;
     }

其输出为"ERROR: code = 256"

如果你真的想要pipe(2), fork(2), execve(2)然后读取pidof命令的输出,你至少应该使用popen(3),因为ReadCommandOutput不在Posix API中;至少

 pid_t thepid = 0;
 FILE* fpidof = popen("pidof /root/test/testProg1");
 if (fpidof) {
    int p=0;
    if (fscanf(fpidof, "%d", &p)>0 && p>0) 
       thepid = (pid_t)p;
    pclose(fpidof);
 }

BTW,你没有指定应该发生什么,如果几个进程(或没有)正在运行testProg1 ....;您还需要检查pclose

的结果

但是你不需要;实际上,您可能希望使用snprintf构建pidof命令(并且您应该害怕代码注入到该命令中,因此适当地引用参数)。您可以通过访问proc(5)文件系统简单地找到您的命令:您将在"/proc/"上打开dir(3),然后在readdir(3)上循环,并且对于每个具有数字名称的条目,如1234(以数字开头),readlink(2)其exe条目,如/proc/1234/exe…)。不要忘记closedir并测试每个系统调用。

请阅读Advanced Linux Programming

请注意,像Poco这样的库或像Qt这样的工具包(它有一个没有任何GUI的QCore层,并提供QProcess ....)可能对你有用。

至于为什么您的pidof失败,我们无法猜测(可能是权限问题,或者可能没有您想要的任何进程)。至少在另一个终端中以root身份运行它。测试它的退出代码,并显示它的stdout &stderr至少为了调试的目的。

另外,更好的方法(假设testProg1是某种服务器应用程序,最多在一个进程中运行)可能是定义不同的约定。您的testProg1可能首先将自己的pid写入/var/run/testProg1.pid,然后您的当前应用程序可能会从该文件中读取pid,并使用kill(2)和0信号号检查进程是否仍然存在。

顺便说一句,您还可以改进crontab(5)条目。您可以让它运行一些shell脚本,该脚本使用logger(1)和(用于调试)运行pidof,并将其输出重定向到其他地方。您也可以阅读cron发送给root的邮件。

最后我使用su命令

解决了这个问题

我用过

         ReadCommanOutput("su -c 'pidof /root/test/testProg1' - root");

         ReadCommanOutput("pidof /root/test/testProg1");

最新更新