c_src: update with new intern methods
[nit.git] / c_src / stream._ffi.c
1 /*
2 Extern implementation of Nit module stream
3 */
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include "stream._ffi.h"
7 #define Array_of_Int_length stream___Array_of_Int_length
8 #define Array_of_Int__index stream___Array_of_Int__index
9 #line 18 "lib/standard/stream.nit"
10
11 #include <unistd.h>
12 #include <poll.h>
13 #include <errno.h>
14 #include <string.h>
15
16 nullable_Int stream___Object_intern_poll___impl( Object recv, Array_of_Int in_fds, Array_of_Int out_fds )
17 {
18 #line 320 "lib/standard/stream.nit"
19
20
21 int in_len, out_len, total_len;
22 struct pollfd *c_fds;
23 sigset_t sigmask;
24 int i;
25 int first_polled_fd = -1;
26 int result;
27
28 in_len = Array_of_Int_length( in_fds );
29 out_len = Array_of_Int_length( out_fds );
30 total_len = in_len + out_len;
31 c_fds = malloc( sizeof(struct pollfd) * total_len );
32
33 /* input streams */
34 for ( i=0; i<in_len; i ++ ) {
35 int fd;
36 fd = Array_of_Int__index( in_fds, i );
37
38 c_fds[i].fd = fd;
39 c_fds[i].events = POLLIN;
40 }
41
42 /* output streams */
43 for ( i=0; i<out_len; i ++ ) {
44 int fd;
45 fd = Array_of_Int__index( out_fds, i );
46
47 c_fds[i].fd = fd;
48 c_fds[i].events = POLLOUT;
49 }
50
51 /* poll all fds, unlimited timeout */
52 result = poll( c_fds, total_len, -1 );
53
54 if ( result > 0 ) {
55 /* analyse results */
56 for ( i=0; i<total_len; i++ )
57 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
58 c_fds[i].revents & POLLHUP ) /* closed */
59 {
60 first_polled_fd = c_fds[i].fd;
61 break;
62 }
63
64 return Int_as_nullable( first_polled_fd );
65 }
66 else if ( result < 0 )
67 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
68
69 return null_Int();
70 }