title: How to set O_NONBLOCKING flag in Unix
body: <p>I am writing a sender/reader IPC C program for class, and I am having trouble setting the O_NONBLOCK flag to 0 so that my reader will block when the buffer it is attempting to read from is empty. Here are the functions I am using:</p>
  
  <pre><code>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 &amp;= ~O_NONBLOCK;
          return fcntl(desc, F_SETFL, oldflags);
  }
  </code></pre>
  
  <p><strong>main()</strong></p>
  
  <pre><code>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 &lt; 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 */
  </code></pre>
  
  <p>The line <code>printf ("nonblocking flag = %d\n", fcntl(fd, F_GETFL, 0));
  </code> is just returning -1 as the flag status. Shouldn't it be 0 if it is cleared?</p>