pipe - demo

扫码查看

点击(此处)折叠或打开

  1. /*
  2. pipe-write
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>

  8. #include <sys/types.h>
  9.        #include <sys/stat.h>
  10.        #include <fcntl.h>
  11. #include <errno.h>

  12. /*
  13. * if do write first, write-app will be blocked until read-app start.
  14. * in runtime, when read-app closed, then write-app will be receive signal(SIGPIPE), and then terminate self.
  15. */

  16. #define FIFO_FFPLAY        "/tmp/my_fifo"

  17. int main()
  18. {
  19.     int fd = mkfifo(FIFO_FFPLAY, 0777);
  20.     if (fd == 0) {
  21.         printf("create FIFO OK.\n");
  22.     }
  23.     else {
  24.         if (EEXIST != errno) {
  25.             printf("mkfifo failed. \n");
  26.             exit(-1);
  27.         }
  28.     }
  29.     
  30.     fd = open(FIFO_FFPLAY, O_WRONLY);
  31.     if (fd < 0) {
  32.         printf("open FIFO failed. \n");
  33.         exit(-1);
  34.     }
  35.     
  36.     printf("Write data to FIFO.\n");
  37.     
  38.     char line[128] = {0};
  39.     int idx = 0;
  40.     while (1) {
  41.         sprintf(line, "%04d.\n 000", idx++);
  42.         printf(line);
  43.         write(fd, line, strlen(line));
  44.         usleep(1000000);
  45.     }
  46.     
  47.     close(fd);
  48.     //unlink(FIFO_FFPLAY);
  49.     
  50.     return 0;
  51. }


点击(此处)折叠或打开

  1. /*
  2. pipe-read
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <string.h>
  9. #include <sys/types.h>
  10.        #include <sys/stat.h>
  11.        #include <fcntl.h>
  12. #include <errno.h>

  13. #define FIFO_FFPLAY        "/tmp/my_fifo"

  14. int main()
  15. {
  16.     int fd = mkfifo(FIFO_FFPLAY, 0777);
  17.     if (fd == 0) {
  18.         printf("create FIFO OK.\n");
  19.     }
  20.     else {
  21.         if (EEXIST != errno) {
  22.             printf("mkfifo failed. \n");
  23.             exit(-1);
  24.         }
  25.     }
  26.     
  27.     fd = open(FIFO_FFPLAY, O_RDONLY);
  28.     if (fd < 0) {
  29.         printf("open FIFO failed. \n");
  30.         exit(-1);
  31.     }
  32.     
  33.     FILE *file = fdopen(fd, "r");
  34.     printf("reading data from FIFO.\n");
  35.     
  36.     char line[128] = {0};
  37.     errno = 0;
  38.     while (1) {
  39.         if (fgets(line, 127, file)) {
  40.         //if (read(fd, line, 127) > 0) {
  41.             printf("### [%s] ###\n", line);
  42.         }
  43.         usleep(100000);
  44.     }
  45.     
  46.     close(fd);
  47.     //unlink(FIFO_FFPLAY);
  48.     
  49.     return 0;
  50. }

10-26 00:06
查看更多