c编程获取sleep后tty的修改时间

标签 c time sleep tty last-modified

我是这个论坛的新手,也是 C 编程的新手。我想显示 sleep 前和 sleep 后的 tty 修改时间(如果我在 sleep 期间在终端上输入内容)。我正在使用以下代码,但如果我将 struct stat 声明为全局变量,这会提供正确的修改时间但不会在 sleep 后更改它。另一方面,我将 struct stat 声明为局部变量,它给了我完全不正确的日期,但似乎在 sleep 后更改了日期。我想弄清楚这两天,但没有运气。请帮忙

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <stddef.h>
#include <string.h>

char *modTime;
void getmt();
time_t modifiedTime;

//struct stat statbuf; //this gives the correct modification time but does not change it   after sleep

int main(int argc, char **argv)
{
    int i, status = 0;
    time_t now;

    if (argc == 1) {
        fprintf(stderr, "usage: %s file \n", argv[0]);
        return(1);
    }

    for (i = 1; i < argc; i++)
    {
        struct stat statbuf;

        if (lstat(argv[i], &statbuf)) {
            perror(argv[i]);
            status = 1;
        }
        else
        {
            getmt();
            time(&now);
            printf("\nNOW %ld\n", now);
            sleep(20);
            time(&now);
            printf("after sleep %ld\n", now);
            getmt();
        }
    }

    return(status);
}

void getmt()
{
    struct stat statbuf; //this does not give correct modification time but changes it after sleep
    time_t modifiedTime;

    //modification time of tty as string
    modTime = ctime(&statbuf.st_mtime);
    printf("\n last modified time as string %s\n", modTime);

    //modification time of tty as long date
    modifiedTime = statbuf.st_mtime;
    printf ("last modified time as long date %ld\n", modifiedTime);
}

最佳答案

getmt() 中的struct stat statbuf 从未被初始化,所以它充满了垃圾值。请注意,虽然它与(注释掉的)全局变量具有相同的名称,但它是一个不同的对象,位于不同的地址,在 getmt() 启动时创建并在 getmt() 返回时再次销毁。

lstat 调用在调用时填充了一个struct stat 对象。您在 per-argv 循环中只调用一次,因此您只会获得一个时间值。您必须在 sleep() 之后再次调用 lstat 以查看修改时间是否已更改。

关于c编程获取sleep后tty的修改时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166326/

相关文章:

c - 为什么 getchar 没有退出?

c - 更快地将整数用作 bool 值?

python - 我如何使用 Python(精确到分钟)计算过去 30 天的时间?

time - 为什么os.time中字段 "hour"的默认值为12?

复合文字和类似函数的宏 : bug in gcc or the C standard?

c - 如何在 C 中打开 4 个字符的字符串?

date - 命令行使用日期和时间重命名文件

bash - 我将如何创建一个 bash 脚本来将 .wav 文件从文件夹 [A] 转换为 mp3 格式。然后将它们移动到新文件夹 [mp3folder]

c - sleep() 会干扰 scanf() 吗?

c# - Windows 7 Phone - 延迟屏幕导航