Introduce old redir program
[lcapit-junk-code.git] / linux-kernel / fake-serial / user-land / fstool.c
blob6307030025f5ab8e712f778691042a0b168fbea3
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <termios.h>
6 #include <unistd.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <errno.h>
11 #define NOT_USED(x) (x = x)
13 struct termios original;
15 /**
16 * close_serial_port - Close a serial port
18 * @param: the port to be closed
20 * Close the specified serial port and sets the
21 * its termios structure to the default settings.
23 static void close_serial_port(int fd)
25 tcsetattr(fd, TCSANOW, &original);
26 close(fd);
29 /**
30 * open_serial_port - Open a serial port
32 * @param port: the port to be opened
34 * @return On success a file descriptor,
35 * -1 otherwise
37 static int open_serial_port(const char *port)
39 int fd, ret;
40 struct termios tio;
42 if (!port) {
43 errno = EINVAL;
44 return -1;
47 fd = open(port, O_RDWR | O_NOCTTY);
48 if (fd < 0)
49 goto out;
51 ret = tcgetattr(fd, &original);
52 if (ret < 0)
53 goto err_out;
55 memset(&tio, 0, sizeof(struct termios));
56 tio.c_cflag = CS8 | CREAD | CRTSCTS | CLOCAL | HUPCL;
57 tio.c_iflag = IGNPAR | IGNBRK;
58 tio.c_oflag = 0;
59 tio.c_lflag = 0;
60 tio.c_cc[VTIME] = 1;
61 tio.c_cc[VMIN] = 0;
63 /* If it fails, we will use default settings. */
64 cfsetispeed(&tio, B115200);
65 cfsetospeed(&tio, B115200);
67 ret = tcflush(fd, TCIFLUSH);
68 if (ret < 0)
69 goto err_out;
71 ret = tcsetattr(fd, TCSANOW, &tio);
72 if (ret)
73 goto err_out;
75 out:
76 return fd;
77 err_out:
78 close(fd);
79 fd = -1;
80 goto out;
83 int main(int argc, char *argv[])
85 int i, fd;
86 size_t count;
87 ssize_t bytes;
88 char *cmd, *p, buf[128];
90 NOT_USED(argc);
92 cmd = argv[2];
93 if (!cmd) {
94 fprintf(stderr, "No cmd.\n");
95 exit(1);
98 fd = open_serial_port(argv[1]);
99 if (fd < -1) {
100 perror("open()");
101 exit(1);
104 for (i = 0; i < (int) strlen(cmd); i++) {
106 bytes = write(fd, &cmd[i], (size_t) 1);
107 if (bytes < 0) {
108 perror("write()");
109 exit(1);
110 } else if (bytes != 1) {
111 fprintf(stderr, "Warning wrote %d instead of 1\n", bytes);
115 p = buf;
116 count = sizeof(buf);
117 memset(p, '\0', count);
118 bytes = 1;
120 while ((p - buf) < (unsigned int) sizeof(buf) && !strchr(buf, '%')) {
121 bytes = read(fd, p, count);
122 if (bytes < 0) {
123 perror("read()");
124 exit(1);
127 p += bytes;
128 count -= bytes;
130 close_serial_port(fd);
132 printf("%s\n", buf);
133 return 0;