How to read time from a file without converting

别说谁变了你拦得住时间么 提交于 2019-12-12 03:00:11

问题


My question is general, but I will explain it using a specific example.

Suppose I need to communicate time between two applications. A simple way is to have one application write the output of gettimeofday() (tv_sec and tv_usec) to a file and let the other app read it. The second app needs to 'convert' the strings in order to get an instance of timeval.

Is there any way to avoid the conversion?

Is there a better way to do this than simple file write/read?


回答1:


Assuming both processes are on the same machine (or at least on machines of the same architecture), the results of std::time() (from <ctime>) will be seconds since the Epoch, and will not need any conversion:

std::time_t seconds_since_epoch = std::time(NULL);

Disclaimer: This is not the best method of ipc and you will need to lock the file for reading while it is being written, etc. Just answering the question.


Update, following comment.

If you need to write a timeval, perhaps the easiest way is to define << and >> operators for timeval and write and read these as text to the file (no need to worry about byte-ordering) as-is (with no conversion):

std::ostream& operator <<(std::ostream& out, timeval const& tv)
{
    return out << tv.tv_sec << " " << tv.tv_usec;
}

std::istream& operator >>(std::istream& is, timeval& tv)
{
    return is >> tv.tv_sec >> tv.tv_usec;
}

This will allow you to do the following (ignoring concurrency):

// Writer
{
    timeval tv;
    gettimeofday(&tv, NULL);
    std::ofstream timefile(filename, std::ofstream::trunc);
    timefile << tv << std::endl;
}

// Reader
{
    timeval tv;
    std::ifstream timefile(filename);
    timefile >> tv;
}

If both process are running concurrently, you'll need to lock the file. Here's an example using Boost:

// Writer
{
    timeval tv;
    gettimeofday(&tv, NULL);
    file_lock lock(filename);

    scoped_lock<file_lock> lock_the_file(lock);

    std::ofstream timefile(filename, std::ofstream::trunc);
    timefile << tv << std::endl;
    timefile.flush();
}

// Reader
{
    timeval tv;
    file_lock lock(filename);

    sharable_lock<file_lock> lock_the_file(lock);

    std::ifstream timefile(filename);
    timefile >> tv;

    std::cout << tv << std::endl;
}

...I've omitted the exception handling (when the file does not exist) for clarity; you'd need to add this to any production-worthy code.



来源:https://stackoverflow.com/questions/14971546/how-to-read-time-from-a-file-without-converting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!