]> rtime.felk.cvut.cz Git - sojka/sterm.git/blobdiff - sterm.c
Never block when opening the port
[sojka/sterm.git] / sterm.c
diff --git a/sterm.c b/sterm.c
index 2402c95dbd3e1c5ae19b0d7d184cb9d9fe62a075..209f83c92df4d42ecd2a13d8c3c58d3e4a2ac73a 100644 (file)
--- a/sterm.c
+++ b/sterm.c
@@ -1,7 +1,7 @@
 /*
  * Simple serial terminal
  *
- * Copyright 2014 Michal Sojka <sojkam1@fel.cvut.cz>
+ * Copyright 2014, 2015 Michal Sojka <sojkam1@fel.cvut.cz>
  *
  * This program is free software: you can redistribute it and/or
  * modify it under the terms of the GNU General Public License as
@@ -101,14 +101,16 @@ void exit_on_escapeseq(const char *buf, int len)
        static const char escseq[] = "\r~.";
        static const char *state = escseq+1;
        int i;
-
        for (i = 0; i < len; i++) {
                if (buf[i] == *state) {
                        state++;
                        if (*state == 0)
                                exit(0);
-               } else
+               } else {
                        state = escseq;
+                       if (buf[i] == *state)
+                               state++;
+               }
        }
 }
 
@@ -207,10 +209,14 @@ int main(int argc, char *argv[])
        }
        atexit(unlock);
 
-       if ((fd = open(dev, O_RDWR)) < 0) {
+       /* O_NONBLOCK is needed to not wait for the CDC signal. See tty_ioctl(4). */
+       if ((fd = open(dev, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) {
                perror(dev);
                exit(1);
        }
+        /* Cancel the efect of O_NONBLOCK flag. */
+       int n = fcntl(fd, F_GETFL, 0);
+        fcntl(fd, F_SETFL, n & ~O_NDELAY);
 
        if (isatty(fd)) {
                CHECK(ioctl(fd, TIOCEXCL, NULL));