C++ 对inotify作出反应并打印事件的程序
我在Ubuntu工作。我想监视一个文件夹并打印子文件夹中弹出的每个事件(打印文件)。 我有以下代码,但它不工作。执行时,没有事件的println 在第二段代码中,我只看到文件夹中的事件。每个子文件夹中的事件不会弹出C++ 对inotify作出反应并打印事件的程序,c++,inotify,C++,Inotify,我在Ubuntu工作。我想监视一个文件夹并打印子文件夹中弹出的每个事件(打印文件)。 我有以下代码,但它不工作。执行时,没有事件的println 在第二段代码中,我只看到文件夹中的事件。每个子文件夹中的事件不会弹出 #include <string> #include <iostream> #include <stdio.h> using namespace std; std::string exec(char* cmd) { FILE* pipe =
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[256];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 256, pipe) != NULL)
result += buffer;
}
pclose(pipe);
cout<<"result is: "<<result<<endl;
return result;
}
int main()
{
//while(1)
//{
string s=exec((char*)"inotifywait -rme create /home/folder/");
cout << s << endl;
//}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
std::string exec(char*cmd){
文件*pipe=popen(cmd,“r”);
如果(!pipe)返回“ERROR”;
字符缓冲区[256];
std::string result=“”;
而(!feof(管道)){
如果(fgets(缓冲区,256,管道)!=NULL)
结果+=缓冲区;
}
pclose(管道);
cout您的第二个解决方案不起作用,因为inotify_add_wait不能递归工作。您必须手动为子目录添加手表。由于这可能会令人讨厌,也可以像第一个示例中一样使用工具inotifywait
您的第一个示例不起作用,因为您一直在从管道中读取。如果您终止inotifywait进程(例如,如果您是机器上唯一的一个人,而这是唯一一个仅使用“killall inotifywait”的inotifywait进程)您将获得输出,因为您将中断从管道读取的循环。如果您在循环内输出某些内容,它也会工作。您的第二个解决方案不工作,因为inotify\u add\u watch无法递归工作。您必须手动为子目录添加手表。因为这可能会很烦人,您还可以像在第一个示例中一样使用工具inotifywait
您的第一个示例不起作用,因为您一直在从管道中读取。如果您终止inotifywait进程(例如,如果您是机器上唯一的一个人,而这是唯一一个仅使用“killall inotifywait”的inotifywait进程)您将获得输出,因为您将中断从管道读取的循环。如果您在循环中输出某些内容,它也会工作。我使用g++代码执行。字符串s没有输出。我使用g++代码执行。字符串s没有输出。
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <iostream>
void processNewFiles(int fd, int wd);
int main(int argc, char** argv)
{
const char* dirPath = "/home/folder/" ;//argv[1];
int fd = inotify_init();
int wd = inotify_add_watch(fd, dirPath, IN_CREATE);
if (wd)
{
processNewFiles(fd, wd);
inotify_rm_watch(fd, wd);
}
}
void processNewFiles(int fd, int wd)
{
bool done = false;
do
{
int qLen = 0;
ioctl(fd, FIONREAD, &qLen);
char* buf = new char[qLen];
int num = read(fd, buf, qLen);
if (num == qLen)
{
inotify_event* iev = reinterpret_cast<inotify_event*>(buf);
if (iev->wd == wd && iev->mask & IN_CREATE)
{
std::cout << "New file created: " << iev->name << std::endl;
}
}
delete [] buf;
} while (!done);
}