title: Receive extra null byte when using serial port
body: <p>I'm writing a program for serial port data transmission on Linux, but find that every time the sender opens the port, the receiver gets an extra null byte <code>'\x00'</code>.</p>
  
  <p>Here's the code of sender:</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;termios.h&gt;
  #include &lt;fcntl.h&gt;
  
  int main(int argc, char* argv[]) {
    int fd_com_ = open("/dev/ttyAM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
  
    struct termios attrs_;
    attrs_.c_iflag = IGNBRK;
    attrs_.c_oflag = 0;
    attrs_.c_cflag = (CLOCAL | CREAD);
    attrs_.c_cflag |= CS8;
    attrs_.c_lflag = 0;
    attrs_.c_cc[VMIN] = 0;
    attrs_.c_cc[VTIME] = 0;
    cfsetspeed(&amp;attrs_, B115200);
  
    tcsetattr(fd_com_, TCSANOW, &amp;attrs_);
  
    const char *s = "abcd";
    write(fd_com_, s, 4);
    sleep(1);
    write(fd_com_, s, 4);
    sleep(1);
    close(fd_com_);
  
    fd_com_ = open("/dev/ttyAM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
    write(fd_com_, s, 4);
  
    return 0;
  }
  </code></pre>
  
  <p>The receiver has the same configuration, but receives <code>"\x00abcdabcd\x00abcd"</code>. How to fix this problem so the receiver could get <code>"abcdabcdabcd"</code>?</p>
  
  <hr>
  
  <p><strong>Update:</strong></p>
  
  <p>The code of receiver:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;termios.h&gt;
  #include &lt;fcntl.h&gt;
  
  int main(int argc, char* argv[]) {
    int fd_com_ = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
  
    struct termios attrs_;
    attrs_.c_iflag = IGNBRK;
    attrs_.c_oflag = 0;
    attrs_.c_cflag = (CLOCAL | CREAD);
    attrs_.c_cflag |= CS8;
    attrs_.c_lflag = 0;
    attrs_.c_cc[VMIN] = 0;
    attrs_.c_cc[VTIME] = 0;
    cfsetspeed(&amp;attrs_, B115200);
  
    tcsetattr(fd_com_, TCSANOW, &amp;attrs_);
  
    char buf[100];
    ssize_t sz;
    while(1) {
      sz = read(fd_com_, buf, 100);
      if (sz &gt; 0) {
        for (ssize_t i=0; i&lt;sz; i++) {
          printf("%02hhx\n", buf[i]);
        }
      }
      sleep(1);
    }
  
    return 0;
  }
  </code></pre>