Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * desc: Fifo example, writes and reads depending on invocation name
- * compile: gcc -o fifo-read fifo.c; ln -svf fifo-read fifo-write
- */
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #define BUF_LEN 256
- static char buf[BUF_LEN];
- #define FIFO "MyFifo"
- int main(int argc, char **argv)
- {
- int pipe_fd;
- int rval;
- int n;
- fd_set rfds;
- rval = mkfifo(FIFO, 0777);
- if (rval != 0)
- fprintf(stderr, "Cannot create fifo ERROR: %s\n", strerror(errno));
- if (!strncmp("fifo-read", argv[0], 9)) {
- do {
- puts("read");
- pipe_fd = open(FIFO, S_IRUSR);
- if (pipe_fd < 0) {
- fprintf(stderr, "Cannot open fifo\n");
- exit(EXIT_FAILURE);
- }
- while ((n = read(pipe_fd, buf, BUF_LEN)) > 0) {
- printf("\"%*s\"\n", n, buf);
- }
- close(pipe_fd);
- } while (1);
- } else if (!strncmp("fifo-write", argv[0], 10)) {
- do {
- puts("read");
- pipe_fd = open(FIFO, S_IWUSR);
- if (pipe_fd < 0) {
- fprintf(stderr, "Cannot open fifo\n");
- exit(EXIT_FAILURE);
- }
- while ((n = read(0, buf, BUF_LEN)) > 0) { /* 0 == stdin */
- write(pipe_fd, buf, n);
- }
- close(pipe_fd);
- } while (1);
- } else {
- fprintf(stderr, "Wrong program name, use fifo-write or fifo-read instead\n");
- return 0;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment