| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
use errors; |
| 5 |
use rt; |
| 6 |
|
| 7 |
// Flags for [[dup]] and [[dup2]] operations. |
| 8 |
export type dupflag = enum { |
| 9 |
NONE = 0, |
| 10 |
|
| 11 |
// Causes [[dup]] and [[dup2]] not to set the CLOEXEC flag on the |
| 12 |
// duplicated file descriptor. By default, CLOEXEC is set. |
| 13 |
NOCLOEXEC = rt::FD_CLOEXEC, |
| 14 |
}; |
| 15 |
|
| 16 |
// Duplicates a file descriptor. |
| 17 |
export fn dup(old: file, flags: dupflag = dupflag::NONE) (file | error) = { |
| 18 |
flags ^= dupflag::NOCLOEXEC; // Invert CLOEXEC |
| 19 |
|
| 20 |
match (rt::dup(old)) { |
| 21 |
case let fd: int => |
| 22 |
const fl = rt::fcntl(fd, rt::F_GETFD, 0)!; |
| 23 |
rt::fcntl(fd, rt::F_SETFD, fl | flags)!; |
| 24 |
return fd; |
| 25 |
case let e: rt::errno => |
| 26 |
return errors::errno(e); |
| 27 |
}; |
| 28 |
}; |
| 29 |
|
| 30 |
// Duplicates a file descriptor and stores the new file at a specific file |
| 31 |
// descriptor number. If the file indicated by "new" already refers to an open |
| 32 |
// file, this file will be closed before the file descriptor is reused. |
| 33 |
export fn dup2( |
| 34 |
old: file, |
| 35 |
new: file, |
| 36 |
flags: dupflag = dupflag::NONE, |
| 37 |
) (file | error) = { |
| 38 |
let flags = flags: int; |
| 39 |
flags ^= rt::FD_CLOEXEC; // Invert CLOEXEC |
| 40 |
if (flags & rt::FD_CLOEXEC != 0) { |
| 41 |
// dup3 has different flags from dup |
| 42 |
flags &= ~rt::FD_CLOEXEC; |
| 43 |
flags |= rt::O_CLOEXEC; |
| 44 |
}; |
| 45 |
|
| 46 |
match (rt::dup3(old, new, flags)) { |
| 47 |
case let fd: int => |
| 48 |
return fd; |
| 49 |
case let e: rt::errno => |
| 50 |
return errors::errno(e); |
| 51 |
}; |
| 52 |
}; |