0
我寫類發件人/讀者IPC C程序,和我有麻煩了O_NONBLOCK標誌設置爲0,這樣我的讀者將阻止當緩衝區它正試圖從是閱讀空。下面是我使用的功能:如何設置O_NONBLOCKING標誌的Unix
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嗎?
謝謝!這確實解決了我的警告,但現在該標誌設置爲2.您是否知道可能導致此問題的原因? – Zach
我認爲你的條件是錯誤的。而不是'if(value!= 0)'你想'if(value == 0)'。 –
它仍然即將到來的2 – Zach