多线程/多进程写FIFO为原子操作(一次写小于PIPE_BUF内容)

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>

#define WRITENUM        4

typedef struct writeattr        writeattr;
struct writeattr{
        int     id;
        int     fd;
};

int     run_flag;
writeattr wattr[WRITENUM];

void *readfifo(void *arg)
{
        int     n, num=0;
        int     fd = (int)arg;
        char    buf[PIPE_BUF];

        while(run_flag){
                n = read(fd, buf, PIPE_BUF);
                if(n < 0)
                        continue;
                if(n != PIPE_BUF){
                        printf("[read]:error:%d,n:%d\n", errno, n);
                        break;
                }
                if(strncmp(buf, &buf[PIPE_BUF/2], PIPE_BUF/2)){
                        printf("[read]:not equal\n");
                        break;
                }
                if(++num % 1000000 == 0)
                        printf("read:%d\n", num);
        }
}
void *writefifo(void *arg)
{
        int     id = ((writeattr*)arg)->id;
        int     fd = ((writeattr*)arg)->fd;
        char    buf[PIPE_BUF];

        memset(buf, '0'+id, PIPE_BUF);
        while(run_flag){
                write(fd, buf, PIPE_BUF);
        }
}
int main()
{
        int     stat;
        char    fn[]="test.fifo";
        int     fd1, fd2, n, s=0;
        pthread_t       th_w[WRITENUM], th_r;
        int     i;
        printf("PIPE_BUF:%d\n", PIPE_BUF);
        /* create fifo */
        mkfifo(fn, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
        if((fd1 = open(fn, O_RDONLY | O_NONBLOCK, 0)) < 0){
                printf("open error\n");
                return 10;
        }
        if((fd2 = open(fn, O_RDWR | O_NONBLOCK, 0)) < 0){
                printf("open error\n");
                return 20;
        }
        /* create thread */
        run_flag = 1;
        for(i=0; i<WRITENUM; i++){
                wattr[i].id = i;
                wattr[i].fd = fd2;
                pthread_create(&th_w[i], NULL, writefifo, &wattr[i]);
        }
        pthread_create(&th_r, NULL, readfifo, fd1);
        /* destroy thread */
        pthread_join(th_r, NULL);
        for(i=0; i<WRITENUM; i++)
                pthread_join(&th_w[i], NULL);
        close(fd1);
        close(fd2);
        return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值