hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

dup.ha (1175B)


      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) (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(old: file, new: file, flags: dupflag) (file | error) = {
     34 	flags ^= dupflag::NOCLOEXEC; // Invert CLOEXEC
     35 
     36 	match (rt::dup3(old, new, flags)) {
     37 	case let fd: int =>
     38 		return fd;
     39 	case let e: rt::errno =>
     40 		return errors::errno(e);
     41 	};
     42 };