gpt4 book ai didi

c - 如何在 Unix 中设置 O_NONBLOCKING 标志

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:13 25 4
gpt4 key购买 nike

我正在为类编写一个发送器/读取器 IPC C 程序,但我无法将 O_NONBLOCK 标志设置为 0,以便我的读取器在尝试读取的缓冲区为空时阻塞。以下是我正在使用的功能:

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 ()
{
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吗?

最佳答案

您正在调用 set_nonblock_flag,第一个参数是一个整数数组。这是来自 fcntl 联机帮助页的片段。第一个参数应该是文件描述符。

SYNOPSIS

   #include <fcntl.h>

int fcntl(int fildes, int cmd, ...);

DESCRIPTION

The fcntl() function shall perform the operations described below on open files. The fildes argument is a file descriptor.

我想你想先调用 pipe,然后再调用 set_nonblock_flag。所以,我认为您真正想要的是以下内容:

int fd[2];
...
pipe(fd);
set_nonblock_flag(fd[0], 0);

关于c - 如何在 Unix 中设置 O_NONBLOCKING 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com