返回
如何实时监控C++子程序创建的文件?
Linux
2024-03-05 07:40:36
实时监控 C++ 子程序创建的文件
问题
在 C++ 程序中执行子程序后,如何实时监视子程序创建的文件?这对于及时获取文件内容至关重要,例如,日志文件或数据输出。
解决方案
有两种方法可以实现此目的:
方法 1:使用 Tail 命令
步骤:
- 在主程序中,使用
tail -F
命令并将其作为分离线程运行:
std::thread t(monitorFile, "a.txt", parentPID);
t.detach();
- 在
monitorFile
函数中:
void monitorFile(const std::string& fName, pid_t pid) {
std::stringstream cmdSS;
cmdSS << "tail -q -F --pid=" << pid << " " << fName
<< " |grep myText"; // 仅打印包含 myText 的行
std::string cmd(cmdSS.str());
system(cmd.c_str());
}
- 使用
system()
运行tail -F
命令,它将实时监视给定文件并打印包含myText
的行。
方法 2:使用 Fork
步骤:
-
使用
fork
创建一个子进程来执行子程序。 -
在父进程中:
thread t(monitorFile, "a.txt", cPID);
t.detach();
-
创建一个分离线程来运行
monitorFile
函数。 -
等待子进程完成。
注意事项:
- 两种方法都使用
monitorFile
函数,它使用grep
命令过滤包含特定文本的行。 - 方法 2 使用
fork
来更好地控制子进程的生命周期。
代码实现
方法 1:
int main() {
pid_t parentPID = getpid();
std::fstream myFstream;
myFstream.open("a.txt", std::fstream::out);
myFstream.close();
std::thread t(monitorFile, "a.txt", parentPID);
t.detach();
runMyScript();
return 0;
}
方法 2:
int main() {
std::fstream myFstream;
myFstream.open("a.txt", std::fstream::out);
myFstream.close();
pid_t cPID = fork();
if (cPID == 0) { // 子进程
execl("/bin/csh", "csh", "my_script", (char *)nullptr);
perror("execl failed");
} else if (cPID > 0) { // 父进程
thread t(monitorFile, "a.txt", cPID);
t.detach();
// 等待 my_script 完成
int status;
waitpid(cPID, &status, 0);
} else {
std::cout << "ERROR" << std::endl;
}
return 0;
}
总结
这篇文章提供了两种方法来实时监视 C++ 子程序创建的文件,这对于获取文件内容并及时采取行动至关重要。方法 1 使用 tail -F
命令,而方法 2 使用 fork
创建一个子进程。根据具体情况选择最合适的方法。