Debian Codegraph @

io/+freebsd/dup.ha

raw
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::dup2(old, -1)) {
21 case let fd: int =>
22 const fl = rt::fcntl(fd, rt::F_GETFD, 0)!;
23 rt::fcntl(fd, rt::F_SETFD, fl | rt::FD_CLOEXEC)!;
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 flags ^= dupflag::NOCLOEXEC; // Invert CLOEXEC
39
40 match (rt::dup2(old, new)) {
41 case let fd: int =>
42 const fl = rt::fcntl(fd, rt::F_GETFD, 0)!;
43 rt::fcntl(fd, rt::F_SETFD, fl | flags)!;
44 return fd;
45 case let e: rt::errno =>
46 return errors::errno(e);
47 };
48 };