Browse Source

sockread: add support for reading data from a pipe

Moritz Warning 10 years ago
parent
commit
04a518498c
2 changed files with 15 additions and 7 deletions
  1. 1
    1
      utils/sockread/Makefile
  2. 14
    6
      utils/sockread/src/main.c

+ 1
- 1
utils/sockread/Makefile View File

@@ -18,7 +18,7 @@ define Package/sockread
18 18
 endef
19 19
 
20 20
 define Package/sockread/description
21
-	sockread reads data from a Unix domain socket
21
+	sockread writes and reads data from a Unix domain socket
22 22
 	represented as a special file on the file system.
23 23
 endef
24 24
 

+ 14
- 6
utils/sockread/src/main.c View File

@@ -3,15 +3,16 @@
3 3
 #include <stdlib.h>
4 4
 #include <errno.h>
5 5
 #include <stddef.h>
6
-#include <stdio.h>
7
-#include <string.h>
6
+#include <unistd.h>
8 7
 #include <sys/socket.h>
9 8
 #include <sys/un.h>
10 9
 
11
-
12 10
 int main(int argc, char *argv[]) {
11
+	char buf[1024];
12
+	ssize_t r;
13
+
13 14
 	if (argc != 2) {
14
-		fprintf(stderr, "Usage: %s <socket>\n", argv[0]);
15
+		fprintf(stderr, "Write to and read from a Unix domain socket.\n\nUsage: %s <socket>\n", argv[0]);
15 16
 		return 1;
16 17
 	}
17 18
 
@@ -36,8 +37,15 @@ int main(int argc, char *argv[]) {
36 37
 		return 1;
37 38
 	}
38 39
 
39
-	char buf[1024];
40
-	ssize_t r;
40
+	/* Check if stdin refers to a terminal */
41
+	if (!isatty(fileno(stdin))) {
42
+		/* Read from stdin and write to socket */
43
+		while (0 < (r = fread(buf, 1, sizeof(buf), stdin))) {
44
+			send(fd, buf, r, 0);
45
+		}
46
+	}
47
+
48
+	/* Read from socket and write to stdout */
41 49
 	while (1) {
42 50
 		r = recv(fd, buf, sizeof(buf), 0);
43 51
 		if (r < 0) {