linux - FIFO写管道fd = open(FIFO_SERVER, O_WRONLY | O_NONBLOCK,0);出现错误

查看:728
本文介绍了linux - FIFO写管道fd = open(FIFO_SERVER, O_WRONLY | O_NONBLOCK,0);出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

这是代码段

这是出现的错误,提示FIFO_SERVER没有定义

请求帮助!!!

解决方案

因为系统默认的fifo权限是000, 所以你需要先修改权限再open
完整的代码如下

read

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

#define FIFO_SERVER "/tmp/myfifo"

main(int argc, char** argv) {
    char buf_r[100];
    int fd;
    int nread;
    if ((mkfifo(FIFO_SERVER, O_CREAT | O_EXCL |O_RDWR) < 0) && (errno != EEXIST))
    {
        perror("can not creat fifoserver");
        exit(1);
    }

    char cmd[100];
    sprintf(cmd, "chmod 704 %s", FIFO_SERVER);
    system(cmd);

    printf("preparing for reading bytes...\n");
    memset(buf_r, 0, sizeof(buf_r));
    fd = open(FIFO_SERVER, O_RDONLY | O_NONBLOCK, 0);
    if (fd == -1) {
        perror("open");
        exit(1);
    }
    while (1)
    {
        memset(buf_r, 0, sizeof(buf_r));
        if ((nread = read(fd, buf_r, 100)) == -1) {
            if (errno == EAGAIN)
                printf("no data yet\n");
        }
        printf("read %s from FIFO\n", buf_r);
        sleep(1);
    }
//    pause();
    close(fd);
    unlink(FIFO_SERVER);
}

write

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

#define FIFO_SERVER "/tmp/myfifo"

int main(int argc, char** argv)
{
    int fd;
    char w_buf[100];
    int nwrite;

    fd = open(FIFO_SERVER, O_WRONLY | O_NONBLOCK,0);
    if (fd == -1)
    {
        perror("open error;no reading process");
        exit(1);
    }
    if (argc == 1)
    {
        printf("please send somenthing\n");
        exit(1);
    }
    strcpy(w_buf, argv[1]);
    if ((nwrite = write(fd, w_buf, 100)) == -1)
    {
        if (errno == EAGAIN)
            printf("the fifo has not been read yet.Please try later\n");
    }
    else
        printf("write %s to the fifo\n", w_buf);
    close(fd);
    return 0;
}

运行

先运行reader, 再运行writer

reader

harriszh Fri 1:03@ ~/trunk/cpp/fifo3$ ./read
preparing for reading bytes...
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read abc from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read abc from FIFO
read  from FIFO
read  from FIFO
read  from FIFO
read  from FIFO

writer

harriszh Fri 1:03@ ~/trunk/cpp/fifo3$ ./write abc
write abc to the fifo
harriszh Fri 1:03@ ~/trunk/cpp/fifo3$ ./write "abc"
write abc to the fifo

这篇关于linux - FIFO写管道fd = open(FIFO_SERVER, O_WRONLY | O_NONBLOCK,0);出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆