/* Simple pipe-based ping-pong microbenchmark. On this Celeron N4120 at 2.5 GHz it takes 19.3 to 19.7 microseconds per round trip, which seems like a lot for a multicore microprocessor that ought to be able to do this without any context switches between processes. That’s only fifty thousand messages a second! If you pass a command-line argument, it preloads the pipe with a single byte, which speeds it up to generally 2.1-3.3 microseconds. */ #include #include #include #include void fail(const char *where) { perror(where); exit(-1); } int main(int argc, char **argv) { int pingfds[2], pongfds[2]; if (pipe(pingfds)) fail("pipe"); if (pipe(pongfds)) fail("pipe #2"); pid_t pid = fork(); if (pid < 0) fail("fork"); if (pid == 0) { /* child */ close(pingfds[1]); /* write end */ close(pongfds[0]); /* read end */ char buf[1]; int bytes; while ((bytes = read(pingfds[0], buf, 1)) == 1) { if (write(pongfds[1], buf, 1) != 1) fail("child write"); } if (bytes < 0) fail("child read"); printf("child ok\n"); return 0; } else { /* parent */ close(pingfds[0]); /* read end */ close(pongfds[1]); /* write end */ if (argc > 1) { if (write(pingfds[1], "&", 1) != 1) fail("prewrite"); } char buf[1]; for (size_t i = 0; i < 1000*1000; i++) { if (write(pingfds[1], "&", 1) != 1) fail("write"); if (read(pongfds[0], buf, 1) != 1) fail("read"); } printf("parent ok\n"); return 0; } }