Pidof从一个后台脚本到另一个后台进程
pidof from a background script for another background process
我写了一个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");
- 如何通过cpp程序运行shell脚本
- 在程序中编写脚本来编写和编译代码
- 如何在c++中使用system()来运行包含空格的python脚本
- 在cygwin中运行c++脚本时发生错误
- 如何将真正的字符串从python c-api转换为python脚本
- 用于将C++代码转换为 Web 程序集的脚本未终止
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 在原子中使用犰狳与脚本
- 我适合在我的构建系统中使用 shell 脚本而不是AX_CHECK_COMPILE_FLAG吗?
- CANoe - 无法在 CAPL 脚本中打开.dll
- 在从Qt调用的Python脚本中导入OpenCV崩溃
- 将数组/向量发送到 c++ 脚本的 cython 示例
- 脚本的多重定义::LState
- 从C++应用获取PowerShell脚本输出
- 用户控制从 c++ 到 java 脚本的 Webassembly 访问调用
- 如何制作启动 Python 脚本的 linux 后台进程(在 c 中)
- 用于检测启动了哪些程序的后台脚本
- 在 C++ 中在后台调用类似于 Unix shell 脚本的函数
- 使用C++或Bash/Shell脚本评估后台linux命令的输出
- Pidof从一个后台脚本到另一个后台进程