我正在为类编写一个发送方/读取器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()
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吗?
发布于 2015-10-26 02:21:33
使用第一个参数作为ints数组调用set_nonblock_flag。这里是fcntl手册的一个片段。第一个参数应该是一个文件描述符。
提要 #包括 int fcntl(include,int,.); 描述 fcntl()函数将对打开的文件执行下面描述的操作。fildes参数是一个文件描述符。
我想你想先打电话给pipe,然后再打给set_nonblock_flag。所以,我想你真正想要的是:
int fd[2];
...
pipe(fd);
set_nonblock_flag(fd[0], 0);https://stackoverflow.com/questions/33337436
复制相似问题