Libuv:Filesystem
libuv provides a wide variety of cross-platform sync and async filesystem operations. All functions defined in this document take a callback, which is allowed to be NULL. If the callback is NULL the request is completed synchronously, otherwise it will be performed asynchronously.
All file operations are run on the threadpool, see Thread pool work scheduling for information on the threadpool size.
Introduce
libuv의 파일시스템은 동기(synchronous)와 비동기(asynchronous), 두 가지 동작을 할 수 있다.
- 동기적으로 동작하기 위해서 콜백(Callback)에 NULL을 전달하면 된다. 이 때, 반환 값으로 libuv error code를 확인하면 된다.
- 비동기로 동작하기 위해 콜백(Callback)을 전달하게 되며, 반환 값을 0이다.
Note
기본적으로 libuv 파일시스템은 소켓 명령들과 다르게 동작한다.
- 소켓 명령은 OS에서 제공하는 Non-Blocking 명령을 사용하며,
- 파일시스템은 함수 내부적으로 Blocking 된다.
그러나 파일시스템은 스레드풀(Thread Pool)에 의한 호출을 적용하고, 이벤트 루프에 알림(notify)을 등록할 수 있다.
File R/W
/**
* open, creat - open and possibly create a file or device.
*
* @return
* return the new file descriptor, or -1 if an error occurred.
*
* @warning
* On Windows libuv uses CreateFileW and thus the file is always opened in binary mode. @n
* Because of this the O_BINARY and O_TEXT flags are not supported.
*
* @see <http://docs.libuv.org/en/v1.x/fs.html>
* @see <http://linux.die.net/man/2/open>
*/
int open(std::string const & path, int flags = (FILE_OPEN_FLAG_READ_WRITE | FILE_OPEN_CREATE), int mode = 0644)
{
uv_fs_t request;
int result = uv_fs_open(nullptr, &request, path.c_str(), flags, mode, nullptr);
uv_fs_req_cleanup(&request);
// Assert Check:
// - Source code: uv/test/test-fs-event.c
// - Method prototype: static void create_file(const char* name)
return result;
}
/**
* @return
* Returns zero on success.
*
* @see <http://docs.libuv.org/en/v1.x/fs.html>
* @see <http://linux.die.net/man/2/close>
*/
bool close(int fd)
{
uv_fs_t request;
int result = uv_fs_close(nullptr, &request, static_cast<uv_file>(fd), nullptr);
uv_fs_req_cleanup(&request);
// Assert Check:
// - Source code: uv/test/test-fs-event.c
// - Method prototype: static void create_file(const char* name)
return (result == 0 ? true : false);
}
/**
* @return
* On success, return the number of bytes written.
*
* @see <http://docs.libuv.org/en/v1.x/fs.html>
* @see <http://linux.die.net/man/2/pwritev>
*/
int write(int fd, char const * buffer, std::size_t buffer_size, int64_t offset)
{
uv_fs_t request;
uv_buf_t buf;
buf.len = buffer_size;
buf.base = const_cast<char*>(buffer);
int result = uv_fs_write(nullptr, &request, static_cast<uv_file>(fd), &buf, 1, offset, nullptr);
uv_fs_req_cleanup(&request);
return result;
}
/**
* @return
* On success, return the number of bytes read.
*
* @see <http://docs.libuv.org/en/v1.x/fs.html>
* @see <http://linux.die.net/man/2/preadv>
*/
int read(int fd, char * buffer, std::size_t buffer_size, int64_t offset)
{
uv_fs_t request;
uv_buf_t buf;
buf.len = buffer_size;
buf.base = buffer;
int result = uv_fs_read(nullptr, &request, static_cast<uv_file>(fd), &buf, 1, offset, nullptr);
uv_fs_req_cleanup(&request);
return result;
}