1 module symmetry.linux.file; 2 import symmetry.sildoc; 3 4 version(Posix): 5 6 int fdopen(string s, int mode) 7 { 8 import core.sys.posix.fcntl: posix_open = open; 9 import core.stdc.errno; 10 import core.stdc..string:strerror; 11 import std..string:fromStringz,toStringz; 12 import std.exception: enforce; 13 import std.format: format; 14 auto result = posix_open(s.toStringz,mode); 15 enforce(result != -1, format!"error %s (%s) opening %s"(strerror(errno).fromStringz,errno,s)); 16 return result; 17 } 18 19 void fdclose(int fd) 20 { 21 import core.sys.posix.unistd: posix_close = close; 22 import core.stdc.errno; 23 import core.stdc..string:strerror; 24 import std..string:fromStringz,toStringz; 25 import std.exception: enforce; 26 import std.format: format; 27 auto result = posix_close(fd); 28 enforce(result != -1, format!"error %s (%s) closing file %s"(strerror(errno).fromStringz,errno,fd)); 29 } 30 31 32 33 int[] fnPipe() 34 { 35 import core.sys.posix.unistd: posix_pipe=pipe; 36 import core.stdc.errno; 37 import core.stdc..string:strerror; 38 import std..string:fromStringz,toStringz; 39 import std.exception: enforce; 40 import std.format: format; 41 42 int[2] fd; 43 auto result = posix_pipe(fd); 44 enforce(result >=0, format!"error %s (%s) for pipe"(errno,strerror(errno).fromStringz)); 45 return fd.dup; 46 } 47 48 49 /// Returns true on success, or false if there was an error 50 // https://stackoverflow.com/questions/1543466/how-do-i-change-a-tcp-socket-to-be-non-blocking 51 bool setSocketBlockingEnabled(int fd, bool blocking) 52 { 53 import core.sys.posix.fcntl : fcntl, F_GETFL, F_SETFL, O_NONBLOCK; 54 if (fd < 0) return false; 55 56 int flags = fcntl(fd, F_GETFL, 0); 57 if (flags == -1) return false; 58 flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK); 59 return fcntl(fd, F_SETFL, flags) == 0; 60 } 61