this repo has no description
1// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
2#include "file.h"
3
4#include <sys/fcntl.h>
5#include <sys/ioctl.h>
6#include <sys/stat.h>
7#include <unistd.h>
8
9#include <cerrno>
10
11#include "utils.h"
12
13namespace py {
14
15int File::close(int fd) { return ::close(fd) < 0 ? -errno : 0; }
16
17int File::isatty(int fd) {
18 errno = 0;
19 int result = ::isatty(fd);
20 if (result == 1) return 1;
21 int saved_errno = errno;
22 return saved_errno == 0 ? 0 : -saved_errno;
23}
24
25int File::isDirectory(int fd) {
26 struct stat statbuf;
27 int result = TEMP_FAILURE_RETRY(::fstat(fd, &statbuf));
28 return result < 0 ? -errno : S_ISDIR(statbuf.st_mode);
29}
30
31int File::isInheritable(int fd) {
32 int result = ::fcntl(fd, F_GETFD);
33 return result < 0 ? -errno : result & FD_CLOEXEC;
34}
35
36int File::open(const char* path, int flags, int mode) {
37 // Set non-inheritable by default
38 int result = TEMP_FAILURE_RETRY(::open(path, flags | O_CLOEXEC, mode));
39 return result < 0 ? -errno : result;
40}
41
42ssize_t File::read(int fd, void* buffer, size_t count) {
43 ssize_t result = TEMP_FAILURE_RETRY(::read(fd, buffer, count));
44 return result < 0 ? -errno : result;
45}
46
47int File::setNoInheritable(int fd) {
48 int result = ::ioctl(fd, FIOCLEX, nullptr);
49 return result < 0 ? -errno : result;
50}
51
52int64_t File::seek(int fd, int64_t offset, int whence) {
53 off_t result = ::lseek(fd, offset, whence);
54 return result < 0 ? -errno : result;
55}
56
57int64_t File::size(int fd) {
58 struct stat statbuf;
59 int result = TEMP_FAILURE_RETRY(::fstat(fd, &statbuf));
60 return result < 0 ? -errno : statbuf.st_size;
61}
62
63int File::truncate(int fd, int64_t size) {
64 int result = TEMP_FAILURE_RETRY(::ftruncate(fd, size));
65 return result < 0 ? -errno : 0;
66}
67
68ssize_t File::write(int fd, const void* buffer, size_t size) {
69 ssize_t result = TEMP_FAILURE_RETRY(::write(fd, buffer, size));
70 return result < 0 ? -errno : result;
71}
72
73const word File::kBinaryFlag = 0;
74const word File::kCreate = O_CREAT;
75const word File::kNoInheritFlag = O_CLOEXEC;
76const word File::kStderr = STDERR_FILENO;
77const word File::kStdin = STDIN_FILENO;
78const word File::kStdout = STDOUT_FILENO;
79const word File::kTruncate = O_TRUNC;
80const word File::kWriteOnly = O_WRONLY;
81
82} // namespace py