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 return ::fstat(fd, &statbuf) < 0 ? -errno : S_ISDIR(statbuf.st_mode);
28}
29
30int File::isInheritable(int fd) {
31 int result = ::fcntl(fd, F_GETFD);
32 return result < 0 ? -errno : result & FD_CLOEXEC;
33}
34
35int File::open(const char* path, int flags, int mode) {
36 int result;
37 do {
38 // Set non-inheritable by default
39 result = ::open(path, flags | O_CLOEXEC, mode);
40 } while (result == -1 && errno == EINTR);
41 return result < 0 ? -errno : result;
42}
43
44ssize_t File::read(int fd, void* buffer, size_t count) {
45 ssize_t result;
46 do {
47 result = ::read(fd, buffer, count);
48 } while (result == -1 && errno == EINTR);
49 return result < 0 ? -errno : result;
50}
51
52int File::setNoInheritable(int fd) {
53 int result = ::ioctl(fd, FIOCLEX, nullptr);
54 return result < 0 ? -errno : result;
55}
56
57int64_t File::seek(int fd, int64_t offset, int whence) {
58 off_t result = ::lseek(fd, offset, whence);
59 return result < 0 ? -errno : result;
60}
61
62int64_t File::size(int fd) {
63 struct stat statbuf;
64 int result = ::fstat(fd, &statbuf);
65 return result < 0 ? -errno : statbuf.st_size;
66}
67
68int File::truncate(int fd, int64_t size) {
69 int result = ::ftruncate(fd, size);
70 return result < 0 ? -errno : 0;
71}
72
73ssize_t File::write(int fd, const void* buffer, size_t size) {
74 ssize_t result;
75 do {
76 result = ::write(fd, buffer, size);
77 } while (result == -1 && errno == EINTR);
78 return result < 0 ? -errno : result;
79}
80
81const word File::kBinaryFlag = 0;
82const word File::kCreate = O_CREAT;
83const word File::kNoInheritFlag = O_CLOEXEC;
84const word File::kStderr = STDERR_FILENO;
85const word File::kStdin = STDIN_FILENO;
86const word File::kStdout = STDOUT_FILENO;
87const word File::kTruncate = O_TRUNC;
88const word File::kWriteOnly = O_WRONLY;
89
90} // namespace py