问题
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