I thought this might be helpful to someone on this forum if they were looking for some code to read data from a serial port.
Nothing to do directly with GTK though.
This code was built to read from a USB serial interface device and can be
#include <stdio.h> /*Standard input/output definitions */
#include <string.h> /*String function definitions */
#include <unistd.h> /*UNIX standard function definitions */
#include <fcntl.h> /*File control definitions */
#include <errno.h> /*Error number definitions */
#include <termios.h> /*POSIX terminal control definitions */
* 'open_port()' - Open serial port 1.
* Returns the file descriptor on success or -1 on error.
int fd; /* File descriptor for the port */
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
/* Could not open the port.*/
perror("open_port: Unable to open /dev/ttyS0 - ");
// fcntl(fd, F_SETFL, 0); /* Blocking READ waits for data in the buffer */
fcntl(fd, F_SETFL, FNDELAY); /* return whatever is there in the buffer */
// n = write(fd, "ATZ\r", 4);
// if (n < 0)
// fputs("write() of 4 bytes failed!\n", stderr);
int main(int argc, char *argv)
int fd = open_port();
struct termios options;
* Get the current options for the port...
* Set the baud rates to B9600...
* Enable the receiver and set local mode...
options.c_cflag |= (CLOCAL | CREAD);
* Set the new options for the port...
tcsetattr(fd, TCSANOW, &options);
/* set to 8N1 mode */
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
options.c_cflag |= CS8; /* Select 8 data bits */
// options.c_cflag &= ~CNEW_RTSCTS;
/* Canonical input is line-oriented. Input characters are put into a buffer
* which can be edited interactively by the user until a
* CR (carriage return) or LF (line feed) character is received.
options.c_lflag |= (ICANON | ECHO | ECHOE);
/* Raw input is unprocessed. Input characters are passed through exactly as
* they are received, when they are received. Generally you'll deselect the
* ICANON, ECHO, ECHOE, and ISIG options when using raw input:
//options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/*Software flow control is enabled using the IXON, IXOFF, and
* IXANY constants:
options.c_iflag |= (IXON | IXOFF | IXANY);
/* To disable software flow control simply mask those bits:*/
//options.c_iflag &= ~(IXON | IXOFF | IXANY);
/* Processed output is selected by setting the OPOST option
* in the c_oflag member:
options.c_oflag |= OPOST;
/* Raw output is selected by resetting the OPOST option
* in the c_oflag member:
//options.c_oflag &= ~OPOST;
int n = read(fd, b, 1);
if(n > -1)