加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

unix i/o nonblocking详解

发布时间:2020-12-15 16:21:14 所属栏目:安全 来源:网络整理
导读:下面是设置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/

下面是设置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 yetn");
            }  
        }
        printf("read %s from FIFOn",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 somenthingn");
        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 latern");
    }
    else
        printf("write %s to the fifon",w_buf);
    close(fd);
    return 0;
}

测试结果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读