example_io.c (1916B)
1 #include <errno.h> 2 #include <fcntl.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <sys/time.h> 7 #include <time.h> 8 #include <unistd.h> 9 10 #include "src/scheduler.h" 11 12 typedef struct { 13 int pipe_fd; 14 int fds[2]; 15 int64_t last_write; 16 } WriterCtx; 17 18 typedef struct { 19 int pipe_fd; 20 int fds[2]; 21 int done; 22 } ReaderCtx; 23 24 static int writer_task(int64_t ts, pt_task_t *task) { 25 static int count = 0; 26 WriterCtx *ctx = task->udata; 27 28 if (ts - ctx->last_write >= 200) { 29 char msg[32]; 30 int len = snprintf(msg, sizeof(msg), "message #%d\n", ++count); 31 write(ctx->pipe_fd, msg, len); 32 ctx->last_write = ts; 33 34 if (count >= 3) { 35 snprintf(msg, sizeof(msg), "quit\n"); 36 write(ctx->pipe_fd, msg, 4); 37 close(ctx->pipe_fd); 38 free(ctx); 39 return SCHED_DONE; 40 } 41 } 42 43 return SCHED_RUNNING; 44 } 45 46 static int reader_task(int64_t ts, pt_task_t *task) { 47 (void)ts; 48 ReaderCtx *ctx = task->udata; 49 50 int ready = sched_has_data(ctx->fds); 51 if (ready >= 0) { 52 char buf[256]; 53 ssize_t n = read(ready, buf, sizeof(buf) - 1); 54 if (n > 0) { 55 buf[n] = '\0'; 56 printf("[reader] %s", buf); 57 } 58 if (n == 0 || (n > 0 && strncmp(buf, "quit\n", 5) == 0)) { 59 ctx->done = 1; 60 } 61 } 62 63 if (ctx->done) { 64 close(ctx->pipe_fd); 65 free(ctx); 66 return SCHED_DONE; 67 } 68 69 return SCHED_RUNNING; 70 } 71 72 int main(void) { 73 int pipefd[2]; 74 if (pipe(pipefd) < 0) { 75 perror("pipe"); 76 return 1; 77 } 78 79 WriterCtx *wctx = calloc(1, sizeof(WriterCtx)); 80 wctx->pipe_fd = pipefd[1]; 81 82 ReaderCtx *rctx = calloc(1, sizeof(ReaderCtx)); 83 rctx->pipe_fd = pipefd[0]; 84 rctx->fds[0] = 1; 85 rctx->fds[1] = rctx->pipe_fd; 86 87 struct timeval now; 88 gettimeofday(&now, NULL); 89 wctx->last_write = (int64_t)now.tv_sec * 1000 + now.tv_usec / 1000; 90 91 sched_create(writer_task, wctx); 92 sched_create(reader_task, rctx); 93 sched_main(); 94 return 0; 95 }