【发布时间】:2016-01-25 01:28:51
【问题描述】:
我正在为类编写一个发送器/读取器 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吗?
【问题讨论】:
标签: c unix ipc nonblocking flags