首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Unix中设置O_NONBLOCKING标志

如何在Unix中设置O_NONBLOCKING标志
EN

Stack Overflow用户
提问于 2015-10-26 02:09:24
回答 1查看 1.1K关注 0票数 0

我正在为类编写一个发送方/读取器IPC C程序,并且我在将O_NONBLOCK标志设置为0时遇到了问题,这样当它试图读取的缓冲区为空时,我的阅读器就会阻塞。下面是我使用的函数:

代码语言:javascript
复制
int set_nonblock_flag(int desc, int value)
{
        int oldflags = fcntl(desc, F_GETFL, 0);
        if (oldflags == -1)
                return -1;
        if (value != 0)
                oldflags |= O_NONBLOCK;
        else
                oldflags &= ~O_NONBLOCK;
        return fcntl(desc, F_SETFL, oldflags);
}

main()

代码语言:javascript
复制
main ()
{
        int fd[2], nbytes;
        char readbuff[26];
        int r_pid = 0;
        int s_pid = 0;

        /* THIS IS ALL UPDATED!*/
        fd[0] = open("fd.txt",O_RDONLY);
        fd[1] = open("fd.txt",O_WRONLY);
        set_nonblock_flag(fd[0], 0);
        set_nonblock_flag(fd[1], 0);
        /* END UPDATES */

        pipe(fd);

        r_pid = fork();
        if (r_pid < 0) /* error */
        {
                fprintf( stderr, "Failed to fork receiver\n" );
                exit( -1 );
        }
        else if (r_pid == 0) /* this is the receiver */
        {
                fprintf( stdout, "I, %d am the receiver!\n", getpid() );

                close( fd[1] ); /* close write end */
                nbytes = read( fd[0], readbuff, 1 );
                printf ("nonblocking flag = %d\n", fcntl(fd, F_GETFL, 0));
                printf ("Nbytes read: %d\n", nbytes );
        }

... /* rest of function removed */

printf ("nonblocking flag = %d\n", fcntl(fd, F_GETFL, 0));只是返回-1作为标志状态。如果它被清除了,不是应该是0吗?

EN

回答 1

Stack Overflow用户

发布于 2015-10-26 02:21:33

使用第一个参数作为ints数组调用set_nonblock_flag。这里是fcntl手册的一个片段。第一个参数应该是一个文件描述符。

提要 #包括 int fcntl(include,int,.); 描述 fcntl()函数将对打开的文件执行下面描述的操作。fildes参数是一个文件描述符。

我想你想先打电话给pipe,然后再打给set_nonblock_flag。所以,我想你真正想要的是:

代码语言:javascript
复制
int fd[2];
...
pipe(fd);
set_nonblock_flag(fd[0], 0);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33337436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档