日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

c/c++ 阻塞和非阻塞,fcntl应用

發(fā)布時間:2023/12/20 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c/c++ 阻塞和非阻塞,fcntl应用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

調(diào)用open函數(shù)時,可以指定打開的文件描述符是以阻塞方式還是以非阻塞方式。
阻塞概念:read函數(shù)在讀設(shè)備或者管道,或者socket的時候,默認(rèn)是阻塞的,也就是說,對方如果沒有發(fā)送數(shù)據(jù)過來,則read函數(shù)就會一直等待數(shù)據(jù)過來,從代碼的角度來說,就是read函數(shù)后面的代碼不會被執(zhí)行。
非阻塞概念:read函數(shù)在讀設(shè)備或者管道,或者socket的時候,對方如果沒有發(fā)送數(shù)據(jù)過來,read函數(shù)也會立即返回,從代碼的角度來說,就是read函數(shù)后面的代碼會馬上被執(zhí)行。

  • 非阻塞方式打開:

    int fd = open("/dev/tty", O_RDWR|O_NONBLOCK);
  • 阻塞方式打開:

    int fd = open("/dev/tty", O_RDWR);

標(biāo)準(zhǔn)輸入輸出和錯誤,實際使用的文件是:/dev/tty,所以下面的例子用這個文件演示。
當(dāng)用非阻塞的時候,如果沒有read到,函數(shù)不會等待,會立即返回,返回值是【-1】,這時errno的值為【11】,用perror打印出來的信息是【Resource temporarily unavailable】
例子:

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h>int main(int argc, char* argv[]){int fd = open("/dev/tty", O_RDWR|O_NONBLOCK);char buf[256];while(1){int ret = read(fd, buf, sizeof buf);if(ret < 0){perror("read:");printf("ret :%d\n", ret);}printf("buf is:%s", buf);printf("haha\n");} }

除了使用【O_NONBLOCK】外,還可以使用fcntl函數(shù),原型如下:

#include <unistd.h> #include <fcntl.h>int fcntl(int fd, int cmd, ... /* arg */ );F_GETFD (void)Return (as the function result) the file descriptor flags; argis ignored. F_SETFD (int)Set the file descriptor flags to the value specified by arg.

例子:

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h>int main(int argc, char* argv[]){int fd = open("/dev/tty", O_RDWR);//先取得fd的flagint flags = fcntl(fd, F_GETFL);//再在原來fd的flag的基礎(chǔ)上,設(shè)置上O_NONBLOCKflags |= O_NONBLOCK;//讓新的flag生效fcntl(fd, F_SETFL, flags);char buf[256];while(1){int ret = read(fd, buf, sizeof buf);if(ret < 0){perror("read:");printf("ret :%d\n", ret);}printf("buf is:%s", buf);printf("haha\n");sleep(1);} }

c/c++ 學(xué)習(xí)互助QQ群:877684253

本人微信:xiaoshitou5854

轉(zhuǎn)載于:https://www.cnblogs.com/xiaoshiwang/p/10759508.html

總結(jié)

以上是生活随笔為你收集整理的c/c++ 阻塞和非阻塞,fcntl应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。