Last active
December 11, 2015 22:28
-
-
Save dbrgn/4669600 to your computer and use it in GitHub Desktop.
Example of a very simple server and client that communicate via named pipes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> // printf, fflush, stdout | |
| #include <fcntl.h> // open, O_RDWR | |
| #include <stdlib.h> // exit | |
| #include <signal.h> // signal, SIGINT | |
| #include <sys/stat.h> // mkfifo | |
| #include <unistd.h> // read | |
| #define QUEUE "request_queue" | |
| #define BUFLEN 20 | |
| void shutdown(int sigtype) { | |
| printf("Server shutting down.\n"); | |
| exit(0); | |
| } | |
| int main (int argc, char* argv[]) { | |
| printf("Starting server...\n"); | |
| // Register shutdown handler | |
| signal(SIGINT, shutdown); | |
| // Create and open named pipe | |
| mkfifo(QUEUE, 0700); | |
| int fd = open(QUEUE, O_RDWR); | |
| // Listen for requests | |
| printf("Ready. Shutdown with CTRL+C.\n"); | |
| char buffer[BUFLEN]; | |
| while (read(fd, buffer, BUFLEN) != 0) { | |
| printf("%s\n", buffer); | |
| fflush(stdout); | |
| } | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> // printf | |
| #include <fcntl.h> // open, O_WRONLY | |
| #include <string.h> // strcopy, strlen | |
| #include <unistd.h> // write, close, sleep | |
| #define QUEUE "request_queue" | |
| #define BUFLEN 20 | |
| int main (int argc, char* argv[]) { | |
| char buffer[BUFLEN]; | |
| strcpy(buffer, "Das ist ein Auftrag"); | |
| for (int i = 0; i < 3; i++) { | |
| int fd = open(QUEUE, O_WRONLY); | |
| write(fd, buffer, strlen(buffer)+1); | |
| close(fd); | |
| sleep(1); | |
| } | |
| printf("Client sent request.\n"); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| danilo@t410:tmp$ gcc server.c -o server -Wall && ./server | |
| Starting server... | |
| Ready. Shutdown with CTRL+C. | |
| Das ist ein Auftrag | |
| Das ist ein Auftrag | |
| Das ist ein Auftrag | |
| ^CServer shutting down. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment