unix i/o nonblocking详解

前端之家收集整理的这篇文章主要介绍了unix i/o nonblocking详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是设置nonblocking的示例,对于理解非常有用的

nonblocking_read.c

#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[]) {
    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 fifo server");
        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 fail");
        exit(1);
    }

    while (1) {
        memset(buf_r,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);
    }

    close(fd);
    unlink(FIFO_SERVER);
}

nonblocking_write.c

#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;
}

测试结果

原文链接:https://www.f2er.com/bash/390880.html

猜你在找的Bash相关文章