another example
[tridge/junkcode.git] / pipes.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sys/time.h>
4 #include <sys/types.h>
5 #include <unistd.h>
6 #include <fcntl.h>
7 #include <errno.h>
8
9 /*******************************************************************
10 find the difference in milliseconds between two struct timeval
11 values
12 ********************************************************************/
13 int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
14 {
15   return((tvalnew->tv_sec - tvalold->tv_sec)*1000 + 
16          ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);  
17 }
18
19 /*******************************************************************
20 sleep for a specified number of milliseconds
21 ********************************************************************/
22 void msleep(int t)
23 {
24   int tdiff=0;
25   struct timeval tval,t1,t2;  
26
27   gettimeofday(&t1, NULL);
28   gettimeofday(&t2, NULL);
29   
30   while (tdiff < t) {
31     tval.tv_sec = (t-tdiff)/1000;
32     tval.tv_usec = 1000*((t-tdiff)%1000);
33  
34     errno = 0;
35     select(0,NULL,NULL, NULL, &tval);
36
37     gettimeofday(&t2, NULL);
38     tdiff = TvalDiff(&t1,&t2);
39   }
40 }
41
42 /****************************************************************************
43 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
44 else
45 if SYSV use O_NDELAY
46 if BSD use FNDELAY
47 ****************************************************************************/
48 int set_blocking(int fd, int set)
49 {
50   int val;
51 #ifdef O_NONBLOCK
52 #define FLAG_TO_SET O_NONBLOCK
53 #else
54 #ifdef SYSV
55 #define FLAG_TO_SET O_NDELAY
56 #else /* BSD */
57 #define FLAG_TO_SET FNDELAY
58 #endif
59 #endif
60
61   if((val = fcntl(fd, F_GETFL, 0)) == -1)
62         return -1;
63   if(set) /* Turn blocking on - ie. clear nonblock flag */
64         val &= ~FLAG_TO_SET;
65   else
66     val |= FLAG_TO_SET;
67   return fcntl( fd, F_SETFL, val);
68 #undef FLAG_TO_SET
69 }
70
71
72 int main()
73 {
74         int fdpair[2];
75         char buf[512] = {0,};
76
77         pipe(fdpair);
78         if (fork()) {
79                 fd_set fds;
80                 while (1) {
81                         int ret;
82
83                         FD_ZERO(&fds);
84                         FD_SET(fdpair[1], &fds);
85
86                         if (select(10, NULL, &fds, NULL, NULL) == 1) {
87                                 printf("writing ..\n"); fflush(stdout);
88                                 ret = write(fdpair[1], buf, sizeof(buf));
89                                 printf("wrote %d\n", ret); fflush(stdout);
90                         }
91                 }
92         } else {
93                 set_blocking(fdpair[0], 0);
94                 while (1) {
95                         int ret = read(fdpair[0], buf, 40);
96                         msleep(100);
97                 }
98         }
99
100         return 0;
101 }