lib/standard: Got rid of FDStream, reified under FStream
[nit.git] / lib / standard / file.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 # Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
6 #
7 # This file is free software, which comes along with NIT. This software is
8 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 # is kept unaltered, and a notification of the changes is added.
12 # You are allowed to redistribute it and sell it, alone or is a part of
13 # another product.
14
15 # File manipulations (create, read, write, etc.)
16 module file
17
18 intrude import stream
19 intrude import ropes
20 import string_search
21 import time
22
23 in "C Header" `{
24 #include <dirent.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <poll.h>
31 #include <errno.h>
32 `}
33
34 # File Abstract Stream
35 abstract class FStream
36 super IOS
37 # The path of the file.
38 var path: nullable String = null
39
40 # The FILE *.
41 private var file: nullable NativeFile = null
42
43 fun file_stat: FileStat do return _file.file_stat
44
45 # File descriptor of this file
46 fun fd: Int do return _file.fileno
47 end
48
49 # File input stream
50 class IFStream
51 super FStream
52 super BufferedIStream
53 super PollableIStream
54 # Misc
55
56 # Open the same file again.
57 # The original path is reused, therefore the reopened file can be a different file.
58 fun reopen
59 do
60 if not eof and not _file.address_is_null then close
61 last_error = null
62 _file = new NativeFile.io_open_read(path.to_cstring)
63 if _file.address_is_null then
64 last_error = new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
65 end_reached = true
66 return
67 end
68 end_reached = false
69 _buffer_pos = 0
70 _buffer.clear
71 end
72
73 redef fun close
74 do
75 if _file.address_is_null then return
76 var i = _file.io_close
77 _buffer.clear
78 end_reached = true
79 end
80
81 redef fun fill_buffer
82 do
83 var nb = _file.io_read(_buffer.items, _buffer.capacity)
84 if nb <= 0 then
85 end_reached = true
86 nb = 0
87 end
88 _buffer.length = nb
89 _buffer_pos = 0
90 end
91
92 # End of file?
93 redef var end_reached: Bool = false
94
95 # Open the file at `path` for reading.
96 init open(path: String)
97 do
98 self.path = path
99 prepare_buffer(10)
100 _file = new NativeFile.io_open_read(path.to_cstring)
101 if _file.address_is_null then
102 last_error = new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
103 end_reached = true
104 end
105 end
106
107 init from_fd(fd: Int) do
108 self.path = ""
109 prepare_buffer(1)
110 _file = fd.fd_to_stream(read_only)
111 if _file.address_is_null then
112 last_error = new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
113 end_reached = true
114 end
115 end
116 end
117
118 # File output stream
119 class OFStream
120 super FStream
121 super OStream
122
123 redef fun write(s)
124 do
125 if last_error != null then return
126 if not _is_writable then
127 last_error = new IOError("Cannot write to non-writable stream")
128 return
129 end
130 if s isa FlatText then
131 write_native(s.to_cstring, s.length)
132 else
133 for i in s.substrings do write_native(i.to_cstring, i.length)
134 end
135 end
136
137 redef fun close
138 do
139 if _file.address_is_null then
140 if last_error != null then return
141 last_error = new IOError("Cannot close unopened write stream")
142 _is_writable = false
143 return
144 end
145 var i = _file.io_close
146 if i != 0 then
147 last_error = new IOError("Close failed due to error {sys.errno.strerror}")
148 end
149 _is_writable = false
150 end
151 redef var is_writable = false
152
153 # Write `len` bytes from `native`.
154 private fun write_native(native: NativeString, len: Int)
155 do
156 if last_error != null then return
157 if not _is_writable then
158 last_error = new IOError("Cannot write to non-writable stream")
159 return
160 end
161 if _file.address_is_null then
162 last_error = new IOError("Writing on a null stream")
163 _is_writable = false
164 return
165 end
166 var err = _file.io_write(native, len)
167 if err != len then
168 # Big problem
169 last_error = new IOError("Problem in writing : {err} {len} \n")
170 end
171 end
172
173 # Open the file at `path` for writing.
174 init open(path: String)
175 do
176 _file = new NativeFile.io_open_write(path.to_cstring)
177 self.path = path
178 _is_writable = true
179 if _file.address_is_null then
180 last_error = new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
181 is_writable = false
182 end
183 end
184
185 # Creates a new File stream from a file descriptor
186 init from_fd(fd: Int) do
187 self.path = ""
188 _file = fd.fd_to_stream(wipe_write)
189 _is_writable = true
190 if _file.address_is_null then
191 last_error = new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
192 _is_writable = false
193 end
194 end
195 end
196
197 redef class Int
198 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
199 #
200 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
201 private fun fd_to_stream(mode: NativeString): NativeFile is extern "file_int_fdtostream"
202 end
203
204 # Constant for read-only file streams
205 private fun read_only: NativeString do return "r".to_cstring
206
207 # Constant for write-only file streams
208 #
209 # If a stream is opened on a file with this method,
210 # it will wipe the previous file if any.
211 # Else, it will create the file.
212 private fun wipe_write: NativeString do return "w".to_cstring
213
214 ###############################################################################
215
216 class Stdin
217 super IFStream
218
219 init do
220 _file = new NativeFile.native_stdin
221 path = "/dev/stdin"
222 prepare_buffer(1)
223 end
224
225 redef fun poll_in: Bool is extern "file_stdin_poll_in"
226 end
227
228 class Stdout
229 super OFStream
230 init do
231 _file = new NativeFile.native_stdout
232 path = "/dev/stdout"
233 _is_writable = true
234 end
235 end
236
237 class Stderr
238 super OFStream
239 init do
240 _file = new NativeFile.native_stderr
241 path = "/dev/stderr"
242 _is_writable = true
243 end
244 end
245
246 ###############################################################################
247
248 redef class Streamable
249 # Like `write_to` but take care of creating the file
250 fun write_to_file(filepath: String)
251 do
252 var stream = new OFStream.open(filepath)
253 write_to(stream)
254 stream.close
255 end
256 end
257
258 redef class String
259 # return true if a file with this names exists
260 fun file_exists: Bool do return to_cstring.file_exists
261
262 # The status of a file. see POSIX stat(2).
263 fun file_stat: FileStat do return to_cstring.file_stat
264
265 # The status of a file or of a symlink. see POSIX lstat(2).
266 fun file_lstat: FileStat do return to_cstring.file_lstat
267
268 # Remove a file, return true if success
269 fun file_delete: Bool do return to_cstring.file_delete
270
271 # Copy content of file at `self` to `dest`
272 fun file_copy_to(dest: String)
273 do
274 var input = new IFStream.open(self)
275 var output = new OFStream.open(dest)
276
277 while not input.eof do
278 var buffer = input.read(1024)
279 output.write buffer
280 end
281
282 input.close
283 output.close
284 end
285
286 # Remove the trailing extension `ext`.
287 #
288 # `ext` usually starts with a dot but could be anything.
289 #
290 # assert "file.txt".strip_extension(".txt") == "file"
291 # assert "file.txt".strip_extension("le.txt") == "fi"
292 # assert "file.txt".strip_extension("xt") == "file.t"
293 #
294 # if `ext` is not present, `self` is returned unmodified.
295 #
296 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
297 fun strip_extension(ext: String): String
298 do
299 if has_suffix(ext) then
300 return substring(0, length - ext.length)
301 end
302 return self
303 end
304
305 # Extract the basename of a path and remove the extension
306 #
307 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
308 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
309 # assert "path/to".basename(".ext") == "to"
310 # assert "path/to/".basename(".ext") == "to"
311 # assert "path".basename("") == "path"
312 # assert "/path".basename("") == "path"
313 # assert "/".basename("") == "/"
314 # assert "".basename("") == ""
315 fun basename(ext: String): String
316 do
317 var l = length - 1 # Index of the last char
318 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
319 if l == 0 then return "/"
320 var pos = chars.last_index_of_from('/', l)
321 var n = self
322 if pos >= 0 then
323 n = substring(pos+1, l-pos)
324 end
325 return n.strip_extension(ext)
326 end
327
328 # Extract the dirname of a path
329 #
330 # assert "/path/to/a_file.ext".dirname == "/path/to"
331 # assert "path/to/a_file.ext".dirname == "path/to"
332 # assert "path/to".dirname == "path"
333 # assert "path/to/".dirname == "path"
334 # assert "path".dirname == "."
335 # assert "/path".dirname == "/"
336 # assert "/".dirname == "/"
337 # assert "".dirname == "."
338 fun dirname: String
339 do
340 var l = length - 1 # Index of the last char
341 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
342 var pos = chars.last_index_of_from('/', l)
343 if pos > 0 then
344 return substring(0, pos)
345 else if pos == 0 then
346 return "/"
347 else
348 return "."
349 end
350 end
351
352 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
353 fun realpath: String do
354 var cs = to_cstring.file_realpath
355 var res = cs.to_s_with_copy
356 # cs.free_malloc # FIXME memory leak
357 return res
358 end
359
360 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
361 # ".." are not resolved if they start the path
362 # starting "/" is not removed
363 # trainling "/" is removed
364 #
365 # Note that the method only wonrk on the string:
366 # * no I/O access is performed
367 # * the validity of the path is not checked
368 #
369 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
370 # assert "../dir/file".simplify_path == "../dir/file"
371 # assert "dir/../../".simplify_path == ".."
372 # assert "dir/..".simplify_path == "."
373 # assert "//absolute//path/".simplify_path == "/absolute/path"
374 # assert "//absolute//../".simplify_path == "/"
375 fun simplify_path: String
376 do
377 var a = self.split_with("/")
378 var a2 = new Array[String]
379 for x in a do
380 if x == "." then continue
381 if x == "" and not a2.is_empty then continue
382 if x == ".." and not a2.is_empty and a2.last != ".." then
383 a2.pop
384 continue
385 end
386 a2.push(x)
387 end
388 if a2.is_empty then return "."
389 if a2.length == 1 and a2.first == "" then return "/"
390 return a2.join("/")
391 end
392
393 # Correctly join two path using the directory separator.
394 #
395 # Using a standard "{self}/{path}" does not work in the following cases:
396 #
397 # * `self` is empty.
398 # * `path` ends with `'/'`.
399 # * `path` starts with `'/'`.
400 #
401 # This method ensures that the join is valid.
402 #
403 # assert "hello".join_path("world") == "hello/world"
404 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
405 # assert "".join_path("world") == "world"
406 # assert "hello".join_path("/world") == "/world"
407 # assert "hello/".join_path("world") == "hello/world"
408 # assert "hello/".join_path("/world") == "/world"
409 #
410 # Note: You may want to use `simplify_path` on the result.
411 #
412 # Note: This method works only with POSIX paths.
413 fun join_path(path: String): String
414 do
415 if path.is_empty then return self
416 if self.is_empty then return path
417 if path.chars[0] == '/' then return path
418 if self.last == '/' then return "{self}{path}"
419 return "{self}/{path}"
420 end
421
422 # Convert the path (`self`) to a program name.
423 #
424 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
425 # used as a program name. In order to do that, prepend `./` if needed.
426 #
427 # assert "foo".to_program_name == "./foo"
428 # assert "/foo".to_program_name == "/foo"
429 # assert "".to_program_name == "./" # At least, your shell will detect the error.
430 fun to_program_name: String do
431 if self.has_prefix("/") then
432 return self
433 else
434 return "./{self}"
435 end
436 end
437
438 # Alias for `join_path`
439 #
440 # assert "hello" / "world" == "hello/world"
441 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
442 # assert "" / "world" == "world"
443 # assert "/hello" / "/world" == "/world"
444 #
445 # This operator is quite useful for chaining changes of path.
446 # The next one being relative to the previous one.
447 #
448 # var a = "foo"
449 # var b = "/bar"
450 # var c = "baz/foobar"
451 # assert a/b/c == "/bar/baz/foobar"
452 fun /(path: String): String do return join_path(path)
453
454 # Returns the relative path needed to go from `self` to `dest`.
455 #
456 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
457 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
458 #
459 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
460 #
461 # In some cases, the result is still independent of the current directory:
462 #
463 # assert "foo/bar".relpath("..") == "../../.."
464 #
465 # In other cases, parts of the current directory may be exhibited:
466 #
467 # var p = "../foo/bar".relpath("baz")
468 # var c = getcwd.basename("")
469 # assert p == "../../{c}/baz"
470 #
471 # For path resolution independent of the current directory (eg. for paths in URL),
472 # or to use an other starting directory than the current directory,
473 # just force absolute paths:
474 #
475 # var start = "/a/b/c/d"
476 # var p2 = (start/"../foo/bar").relpath(start/"baz")
477 # assert p2 == "../../d/baz"
478 #
479 #
480 # Neither `self` or `dest` has to be real paths or to exist in directories since
481 # the resolution is only done with string manipulations and without any access to
482 # the underlying file system.
483 #
484 # If `self` and `dest` are the same directory, the empty string is returned:
485 #
486 # assert "foo".relpath("foo") == ""
487 # assert "foo/../bar".relpath("bar") == ""
488 #
489 # The empty string and "." designate both the current directory:
490 #
491 # assert "".relpath("foo/bar") == "foo/bar"
492 # assert ".".relpath("foo/bar") == "foo/bar"
493 # assert "foo/bar".relpath("") == "../.."
494 # assert "/" + "/".relpath(".") == getcwd
495 fun relpath(dest: String): String
496 do
497 var cwd = getcwd
498 var from = (cwd/self).simplify_path.split("/")
499 if from.last.is_empty then from.pop # case for the root directory
500 var to = (cwd/dest).simplify_path.split("/")
501 if to.last.is_empty then to.pop # case for the root directory
502
503 # Remove common prefixes
504 while not from.is_empty and not to.is_empty and from.first == to.first do
505 from.shift
506 to.shift
507 end
508
509 # Result is going up in `from` with ".." then going down following `to`
510 var from_len = from.length
511 if from_len == 0 then return to.join("/")
512 var up = "../"*(from_len-1) + ".."
513 if to.is_empty then return up
514 var res = up + "/" + to.join("/")
515 return res
516 end
517
518 # Create a directory (and all intermediate directories if needed)
519 fun mkdir
520 do
521 var dirs = self.split_with("/")
522 var path = new FlatBuffer
523 if dirs.is_empty then return
524 if dirs[0].is_empty then
525 # it was a starting /
526 path.add('/')
527 end
528 for d in dirs do
529 if d.is_empty then continue
530 path.append(d)
531 path.add('/')
532 path.to_s.to_cstring.file_mkdir
533 end
534 end
535
536 # Delete a directory and all of its content, return `true` on success
537 #
538 # Does not go through symbolic links and may get stuck in a cycle if there
539 # is a cycle in the filesystem.
540 fun rmdir: Bool
541 do
542 var ok = true
543 for file in self.files do
544 var file_path = self.join_path(file)
545 var stat = file_path.file_lstat
546 if stat.is_dir then
547 ok = file_path.rmdir and ok
548 else
549 ok = file_path.file_delete and ok
550 end
551 stat.free
552 end
553
554 # Delete the directory itself
555 if ok then to_cstring.rmdir
556
557 return ok
558 end
559
560 # Change the current working directory
561 #
562 # "/etc".chdir
563 # assert getcwd == "/etc"
564 # "..".chdir
565 # assert getcwd == "/"
566 #
567 # TODO: errno
568 fun chdir do to_cstring.file_chdir
569
570 # Return right-most extension (without the dot)
571 #
572 # Only the last extension is returned.
573 # There is no special case for combined extensions.
574 #
575 # assert "file.txt".file_extension == "txt"
576 # assert "file.tar.gz".file_extension == "gz"
577 #
578 # For file without extension, `null` is returned.
579 # Hoever, for trailing dot, `""` is returned.
580 #
581 # assert "file".file_extension == null
582 # assert "file.".file_extension == ""
583 #
584 # The starting dot of hidden files is never considered.
585 #
586 # assert ".file.txt".file_extension == "txt"
587 # assert ".file".file_extension == null
588 fun file_extension: nullable String
589 do
590 var last_slash = chars.last_index_of('.')
591 if last_slash > 0 then
592 return substring( last_slash+1, length )
593 else
594 return null
595 end
596 end
597
598 # returns files contained within the directory represented by self
599 fun files : Set[ String ] is extern import HashSet[String], HashSet[String].add, NativeString.to_s, String.to_cstring, HashSet[String].as(Set[String]) `{
600 char *dir_path;
601 DIR *dir;
602
603 dir_path = String_to_cstring( recv );
604 if ((dir = opendir(dir_path)) == NULL)
605 {
606 perror( dir_path );
607 exit( 1 );
608 }
609 else
610 {
611 HashSet_of_String results;
612 String file_name;
613 struct dirent *de;
614
615 results = new_HashSet_of_String();
616
617 while ( ( de = readdir( dir ) ) != NULL )
618 if ( strcmp( de->d_name, ".." ) != 0 &&
619 strcmp( de->d_name, "." ) != 0 )
620 {
621 file_name = NativeString_to_s( strdup( de->d_name ) );
622 HashSet_of_String_add( results, file_name );
623 }
624
625 closedir( dir );
626 return HashSet_of_String_as_Set_of_String( results );
627 }
628 `}
629 end
630
631 redef class NativeString
632 private fun file_exists: Bool is extern "string_NativeString_NativeString_file_exists_0"
633 private fun file_stat: FileStat is extern "string_NativeString_NativeString_file_stat_0"
634 private fun file_lstat: FileStat `{
635 struct stat* stat_element;
636 int res;
637 stat_element = malloc(sizeof(struct stat));
638 res = lstat(recv, stat_element);
639 if (res == -1) return NULL;
640 return stat_element;
641 `}
642 private fun file_mkdir: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
643 private fun rmdir: Bool `{ return rmdir(recv); `}
644 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
645 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
646 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
647 end
648
649 # This class is system dependent ... must reify the vfs
650 extern class FileStat `{ struct stat * `}
651 # Returns the permission bits of file
652 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
653 # Returns the last access time
654 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
655 # Returns the last status change time
656 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
657 # Returns the last modification time
658 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
659 # Returns the size
660 fun size: Int is extern "file_FileStat_FileStat_size_0"
661
662 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
663 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
664 # Returns true if it is a directory
665 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
666 # Returns true if it is a character device
667 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
668 # Returns true if it is a block device
669 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
670 # Returns true if the type is fifo
671 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
672 # Returns true if the type is a link
673 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
674 # Returns true if the type is a socket
675 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
676 end
677
678 # Instance of this class are standard FILE * pointers
679 private extern class NativeFile `{ FILE* `}
680 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
681 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
682 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
683 fun file_stat: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
684 fun fileno: Int `{ return fileno(recv); `}
685
686 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
687 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
688 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
689 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
690 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
691 end
692
693 redef class Sys
694
695 # Standard input
696 var stdin: PollableIStream = new Stdin is protected writable
697
698 # Standard output
699 var stdout: OStream = new Stdout is protected writable
700
701 # Standard output for errors
702 var stderr: OStream = new Stderr is protected writable
703
704 # Enumeration for buffer mode full (flushes when buffer is full)
705 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
706 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
707 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
708 # Enumeration for buffer mode none (flushes ASAP when something is written)
709 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
710
711 # returns first available stream to read or write to
712 # return null on interruption (possibly a signal)
713 protected fun poll( streams : Sequence[FStream] ) : nullable FStream
714 do
715 var in_fds = new Array[Int]
716 var out_fds = new Array[Int]
717 var fd_to_stream = new HashMap[Int,FStream]
718 for s in streams do
719 var fd = s.fd
720 if s isa IFStream then in_fds.add( fd )
721 if s isa OFStream then out_fds.add( fd )
722
723 fd_to_stream[fd] = s
724 end
725
726 var polled_fd = intern_poll( in_fds, out_fds )
727
728 if polled_fd == null then
729 return null
730 else
731 return fd_to_stream[polled_fd]
732 end
733 end
734
735 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]) : nullable Int is extern import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
736 int in_len, out_len, total_len;
737 struct pollfd *c_fds;
738 sigset_t sigmask;
739 int i;
740 int first_polled_fd = -1;
741 int result;
742
743 in_len = Array_of_Int_length( in_fds );
744 out_len = Array_of_Int_length( out_fds );
745 total_len = in_len + out_len;
746 c_fds = malloc( sizeof(struct pollfd) * total_len );
747
748 /* input streams */
749 for ( i=0; i<in_len; i ++ ) {
750 int fd;
751 fd = Array_of_Int__index( in_fds, i );
752
753 c_fds[i].fd = fd;
754 c_fds[i].events = POLLIN;
755 }
756
757 /* output streams */
758 for ( i=0; i<out_len; i ++ ) {
759 int fd;
760 fd = Array_of_Int__index( out_fds, i );
761
762 c_fds[i].fd = fd;
763 c_fds[i].events = POLLOUT;
764 }
765
766 /* poll all fds, unlimited timeout */
767 result = poll( c_fds, total_len, -1 );
768
769 if ( result > 0 ) {
770 /* analyse results */
771 for ( i=0; i<total_len; i++ )
772 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
773 c_fds[i].revents & POLLHUP ) /* closed */
774 {
775 first_polled_fd = c_fds[i].fd;
776 break;
777 }
778
779 return Int_as_nullable( first_polled_fd );
780 }
781 else if ( result < 0 )
782 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
783
784 return null_Int();
785 `}
786
787 end
788
789 # Print `objects` on the standard output (`stdout`).
790 protected fun printn(objects: Object...)
791 do
792 sys.stdout.write(objects.to_s)
793 end
794
795 # Print an `object` on the standard output (`stdout`) and add a newline.
796 protected fun print(object: Object)
797 do
798 sys.stdout.write(object.to_s)
799 sys.stdout.write("\n")
800 end
801
802 # Read a character from the standard input (`stdin`).
803 protected fun getc: Char
804 do
805 return sys.stdin.read_char.ascii
806 end
807
808 # Read a line from the standard input (`stdin`).
809 protected fun gets: String
810 do
811 return sys.stdin.read_line
812 end
813
814 # Return the working (current) directory
815 protected fun getcwd: String do return file_getcwd.to_s
816 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"