• 有名管道


    write.c

    #include <stdio.h>  
    #include <stdlib.h>  
    #include <string.h>  
    #include <fcntl.h>  
    #include <limits.h>  
    #include <sys/types.h>  
    #include <sys/stat.h>  
    
    #define FIFO_NAME "/dev/my_fifo"  
    #define BUFFER_SIZE 20
    #define TEN_MEG (100)  
      
    int main()  
    {  
        int pipe_fd;  
        int res;  
        int open_mode = O_WRONLY;  
        int i=0;
        int bytes = 0;  
        char buffer[BUFFER_SIZE];  
      
        if (access(FIFO_NAME, F_OK) == -1)  
        {  
            res = mkfifo(FIFO_NAME, 0777);  
            if (res != 0)  
            {  
                fprintf(stderr, "Could not create fifo %s
    ", FIFO_NAME);  
                exit(EXIT_FAILURE);  
            }  
        }  
      
      //在这里会阻塞,直到read的open
        pipe_fd = open(FIFO_NAME, open_mode);  
        if (pipe_fd != -1)  
        {  
            
            while (bytes < TEN_MEG)  
            {  
                sleep(1);
                i++;
                memset(buffer, i, sizeof(buffer));
                res = write(pipe_fd, buffer, BUFFER_SIZE);  
                if (res == -1)  
                {  
                    fprintf(stderr, "Write error on pipe
    ");  
                    exit(EXIT_FAILURE);  
                }  
                bytes += res;  
            }  
            close(pipe_fd);  
        }  
        else  
        {  
            exit(EXIT_FAILURE);  
        }  
      
        printf("write: finish bytes=%d
    ", bytes);  
        exit(EXIT_SUCCESS);  
    }

    read.c

    #include <stdio.h>  
    #include <stdlib.h>  
    #include <string.h>  
    #include <fcntl.h>  
    #include <limits.h>  
    #include <sys/types.h>  
    #include <sys/stat.h>  
      
      
    #define FIFO_NAME "/dev/my_fifo"  
    #define BUFFER_SIZE 1  
      
    int main()  
    {  
        int pipe_fd;  
        int res;  
      
        int open_mode = O_RDONLY;  
        char buffer[BUFFER_SIZE];  
        int bytes = 0;  
      
        memset(buffer, '', sizeof(buffer));  
      
      //在这里会阻塞,直到write的open
        pipe_fd = open(FIFO_NAME, open_mode);  
    if (pipe_fd != -1)  
        {  
            do{  
                memset(buffer,0x0, sizeof(buffer));
           //当无数据可读的时候会阻塞在这里 res
    = read(pipe_fd, buffer, BUFFER_SIZE); bytes += res; }while(1); close(pipe_fd); } else { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
  • 相关阅读:
    cgic: CGI的C函数库
    linux下的webserver BOA及CGIC库的使用指南(转帖)
    UDP 收/发 广播包
    winsock 收发广播包
    Linux系统下UDP发送和接收广播消息小例子
    uboot里读sd卡内容
    uboot从SD卡烧写内核和文件系统
    intellij 创建一个文件自动就add到git了,这个怎么取消
    内部类和外部类之间的相互调用
    JDK8的新特性——Lambda表达式
  • 原文地址:https://www.cnblogs.com/maogefff/p/8662742.html
Copyright © 2020-2023  润新知