title: Serial Communication in C for Raspberry Pi
body: <p>I want to make two Raspberry Pi send message to each other using ZigBee protocol.
  I have connected XBee S2C (ZigBee) module to Raspberry Pi using USB Explorer (CH430g). 
  I had written a python script which will do the desired work,</p>
  
  <pre><code>import serial
  
  ser = serial.Serial('/dev/ttyUSB0', 9600)
  
  while True:
      incoming = ser.readline().strip()
      print ('%s' %incoming.decode())
      string = input("") + '\n'
      ser.write(string.encode())
  </code></pre>
  
  <p>But I need a C program to do the same,
  I looked into <a href="https://github.com/crayzeewulf/libserial" rel="nofollow noreferrer">libserial</a> library for C and C++, found that it's buggy and never compiled for me.</p>
  
  <p>I tried <a href="https://stackoverflow.com/questions/17254923/raspberry-pi-uart-program-in-c-using-termios-receives-garbage-rx-and-tx-are-con#51606702">this thread</a> it works pretty well,  but at the receiver side I need to keep  <code>read(fd, &amp;buffer, sizeof(buffer));</code> in a <code>while</code> loop to continuously open for listening unlike a C socket program where <code>read()</code> function will halt till it receives the data just like my python script will wait in line <code>incoming = ser.readline().strip()</code> till it receives some message.</p>
  
  <p>Is there any solution for it without using <code>while</code> loop ?</p>
  
  <p><strong>Edit 1:</strong></p>
  
  <p>In aforementioned python code, while loop is used to receive multiple messages. The line <code>incoming = ser.readline().strip()</code> will catch the message, process it and waits for next message since its in a <code>while</code> loop.</p>
  
  <p>In C if my code is something like this:</p>
  
  <pre><code>while(1){
      str = read();
      //some processing
      }
  </code></pre>
  
  <p>it throws error since <code>read</code> is not halting till it gets the data, it's just returning read fail. Since the read data is <code>NULL</code> the post processing of the data will throw an error. 
  To make it work I have introduce another <code>while</code> loop like this:</p>
  
  <pre><code> while(1){
      while(1){
          str = read();
          if(str!=NULL)
              break;
          }
      //some processing
      }
  </code></pre>
  
  <p>I want to eliminate this extra loop and make <code>read()</code> to wait for the message. 
  PS: I'm opening serial device like this: <code>uart0_filestream = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);</code></p>