memgraph/include/utils/sys.hpp

60 lines
1.4 KiB
C++
Raw Normal View History

2015-11-26 09:52:51 +08:00
#pragma once
2016-09-08 20:25:52 +08:00
#include <cassert>
#include <errno.h>
#include <fstream>
2015-11-26 09:52:51 +08:00
#include <linux/futex.h>
2016-09-08 20:25:52 +08:00
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
2015-11-26 09:52:51 +08:00
#include <sys/time.h>
2016-09-08 20:25:52 +08:00
#include <sys/types.h>
#include <unistd.h>
2015-11-26 09:52:51 +08:00
namespace sys
{
2016-09-09 23:14:20 +08:00
// Code from stackoverflow:
// http://stackoverflow.com/questions/676787/how-to-do-fsync-on-an-ofstream
2016-09-08 20:25:52 +08:00
// Extracts FILE* from streams in std.
2016-09-09 23:14:20 +08:00
inline int GetFileDescriptor(std::filebuf &filebuf)
2016-09-08 20:25:52 +08:00
{
2016-09-09 23:14:20 +08:00
class my_filebuf : public std::filebuf
2016-09-08 20:25:52 +08:00
{
2016-09-09 23:14:20 +08:00
public:
int handle() { return _M_file.fd(); }
};
2016-09-08 20:25:52 +08:00
2016-09-09 23:14:20 +08:00
return static_cast<my_filebuf &>(filebuf).handle();
}
2016-09-08 20:25:52 +08:00
inline int futex(void *addr1, int op, int val1, const struct timespec *timeout,
void *addr2, int val3)
2015-11-26 09:52:51 +08:00
{
return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
2016-09-08 20:25:52 +08:00
};
// Ensures that everything written to file will be writen on disk when the
// function call returns. !=0 if error occured
template <class STREAM>
inline size_t flush_file_to_disk(STREAM &file)
{
file.flush();
2016-09-09 23:14:20 +08:00
if (fsync(GetFileDescriptor(*file.rdbuf())) == 0) {
2016-09-08 20:25:52 +08:00
return 0;
}
return errno;
};
// True if succesffull
inline bool ensure_directory_exists(std::string const &path)
{
struct stat st = {0};
2015-11-26 09:52:51 +08:00
2016-09-08 20:25:52 +08:00
if (stat(path.c_str(), &st) == -1) {
return mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0;
}
return true;
2015-11-26 09:52:51 +08:00
}
2016-09-08 20:25:52 +08:00
};