wutil: Give narrow versions of a few functions

Note that this isn't technically *w*util, but the differences between
the functions are basically just whether they do the wcs2string
themselves or not.
This commit is contained in:
Fabian Homborg 2019-05-31 09:33:50 +02:00
parent 4e03d3c264
commit bc19647be2
2 changed files with 19 additions and 6 deletions

View File

@ -189,20 +189,19 @@ bool set_cloexec(int fd) {
return fcntl(fd, F_SETFD, flags | FD_CLOEXEC) >= 0;
}
static int wopen_internal(const wcstring &pathname, int flags, mode_t mode, bool cloexec) {
int open_cloexec(const std::string &cstring, int flags, mode_t mode, bool cloexec) {
ASSERT_IS_NOT_FORKED_CHILD();
cstring tmp = wcs2string(pathname);
int fd;
#ifdef O_CLOEXEC
// Prefer to use O_CLOEXEC. It has to both be defined and nonzero.
if (cloexec) {
fd = open(tmp.c_str(), flags | O_CLOEXEC, mode);
fd = open(cstring.c_str(), flags | O_CLOEXEC, mode);
} else {
fd = open(tmp.c_str(), flags, mode);
fd = open(cstring.c_str(), flags, mode);
}
#else
fd = open(tmp.c_str(), flags, mode);
fd = open(cstring.c_str(), flags, mode);
if (fd >= 0 && !set_cloexec(fd)) {
close(fd);
fd = -1;
@ -212,7 +211,8 @@ static int wopen_internal(const wcstring &pathname, int flags, mode_t mode, bool
}
int wopen_cloexec(const wcstring &pathname, int flags, mode_t mode) {
return wopen_internal(pathname, flags, mode, true);
cstring tmp = wcs2string(pathname);
return open_cloexec(tmp, flags, mode, true);
}
DIR *wopendir(const wcstring &name) {
@ -815,6 +815,15 @@ file_id_t file_id_for_path(const wcstring &path) {
return result;
}
file_id_t file_id_for_path(const std::string &path) {
file_id_t result = kInvalidFileID;
struct stat buf = {};
if (0 == stat(path.c_str(), &buf)) {
result = file_id_t::from_stat(buf);
}
return result;
}
bool file_id_t::operator==(const file_id_t &rhs) const { return this->compare_file_id(rhs) == 0; }
bool file_id_t::operator!=(const file_id_t &rhs) const { return !(*this == rhs); }

View File

@ -28,6 +28,9 @@ bool set_cloexec(int fd);
/// possible).
int wopen_cloexec(const wcstring &pathname, int flags, mode_t mode = 0);
/// Narrow version of wopen_cloexec.
int open_cloexec(const std::string &cstring, int flags, mode_t mode = 0, bool cloexec = true);
/// Mark an fd as nonblocking; returns errno or 0 on success.
int make_fd_nonblocking(int fd);
@ -195,6 +198,7 @@ struct hash<file_id_t> {
file_id_t file_id_for_fd(int fd);
file_id_t file_id_for_path(const wcstring &path);
file_id_t file_id_for_path(const std::string &path);
extern const file_id_t kInvalidFileID;