当该应用程序中加速文件的最后一个修改时间发生更改时,如何重新启动应用程序

how to reboot the application when there is a change in last modification time of an accesed file in that application

本文关键字:应用程序 重新启动 时间 加速 文件 修改 最后一个      更新时间:2023-10-16

我是线程编程的新手。我正在尝试创建一个应用程序,该应用程序不断检查某些文件的最后一个修改时间并在此时间更改时退出程序。

请在下面找到我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <cerrno>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 2
void *getFileCreationTime(void *path) {
    const char *pt;
    pt=(const char *)path;
    struct stat attr;
    stat("/home/utthunga/shmrp.cpp", &attr);
    while(1){
        char  *timestamp= ctime(&attr.st_mtime);
        if(timestamp)
        {
            cout<<"Last modified time: %s"<< ctime(&attr.st_mtime)<<endl;
            cout<<"No changes has been made to the file"<<endl;
            sleep(4);
        }
        else 
        {
            cout<<"Last modified time: %s"<< ctime(&attr.st_mtime)<<endl;
            cout<<"Time stamp has been changed"<<endl;
            exit(0);
        }
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_t threads[NUM_THREADS];
    int i;
    int rc;
    for( i = 0; i < NUM_THREADS-1; i++ ) 
        rc = pthread_create(&threads[i], NULL, getFileCreationTime, (void *)i);
    pthread_exit(NULL);
    return 0;
}

任何人都可以告诉我,我必须实施什么更改才能连续检查该文件的最后一个修改时间并在此时间更改时退出应用程序?

第一次检索文件的修改时间后,您需要保存它,因此您可以将其与之后的后续值进行比较。

尝试更多这样的东西:

void* getFileCreationTime(void *) { 
    const char *path = "/home/utthunga/shmrp.cpp";
    struct stat attr;
    if (stat(path, &attr) < 0) {
        cout << "stat error" << endl;
        exit(0);
    }
    time_t mtime = attr.st_mtime;
    cout << "Last modified time: " << ctime(&mtime) << endl;
    while(1) {
        sleep(4);
        if (stat(path, &attr) < 0) {
            cout << "stat error" << endl;
            exit(0);
        }
        if (attr.st_mtime != mtime) {
            cout << "Time stamp has been changed" << endl;
            exit(0);
        } else {
            cout << "No changes have been made to the file" << endl;
        }
    }
    pthread_exit(NULL);
}
相关文章: