intirain 4 жил өмнө
parent
commit
18363a653a
2 өөрчлөгдсөн 59 нэмэгдсэн , 10 устгасан
  1. 1 1
      include/vcc/version.h
  2. 58 9
      main.c

+ 1 - 1
include/vcc/version.h

@@ -1 +1 @@
-#define VCCD_VERSION "vccd 0.1.0 Fri Mar  4 22:03:55 CST 2022 root"
+#define VCCD_VERSION "vccd 0.1.0 Sat Mar  5 15:52:51 CST 2022 root"

+ 58 - 9
main.c

@@ -31,12 +31,15 @@
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
+#include <poll.h>
+#include <signal.h>
 
 #include <vcc/vcc.h>
 #include <vcc/version.h>
 
 
 int fd;
+static unsigned char empty_package[REQ_SIZE];
 
 static int usage(void) {
 	fprintf(stderr, "Usage: vcc [server]\n");
@@ -106,33 +109,79 @@ static int send_msg(const char *msg) {
 	return 0;
 }
 
+
 static int read_msg(char *buf) {
 	return read(fd, buf, REQ_SIZE);
 }
 
 
+void alarm_handler(int nr) {
+	alarm(1);
+
+	empty_package[0] = 0xff;
+	write(fd, empty_package, REQ_SIZE);
+
+	return;
+}
+
+static int setup_alarm(void) {
+	struct sigaction act;
+
+	act.sa_handler = alarm_handler;
+	act.sa_flags = SA_RESTART;
+
+	sigaction(SIGALRM, &act, NULL);
+
+	alarm(1);
+
+	return 0;
+}
+
+
 int main(int argc, const char **argv) {
-	char *buf;
+	char buf[REQ_SIZE];
+	int pid;
 
 	if (unlikely(argc != 1 && argc != 2)) 
 		return usage();
 
 	printf(VCCD_VERSION "\n");
 
-	if (unlikely(!(buf = malloc(REQ_SIZE)))) {
-		fprintf(stderr, "*** malloc() failed\n");
+	init_socket(argv[1] ? argv[1] : "124.223.105.230");
+
+	printf("Connected to server. \n");
+
+	if ((pid = fork())) {
+		/* receive messages */
 
-		return 1;
+		setup_alarm();
+
+		for (;;) {
+			memset(buf, 0, REQ_SIZE);
+
+			if (read_msg(buf) == -1) {
+				printf("Server closed\n");
+
+				break;
+			}
+
+			printf("New message: %s\n", buf);
+		}
 	}
 
-	init_socket(argv[1] ? argv[1] : "124.223.105.230");
+	else 
+		for (;;) {
+			memset(buf, 0, REQ_SIZE);
+			read(0, buf, REQ_SIZE);
 
-	printf("Connected to server. \n");
+			if (!strcmp(buf, "quit")) 
+				break;
 
-	send_msg("Hello, server! \n");
-	read_msg(buf);
+			send_msg(buf);
+		}
 
-	printf(buf);
+	close(fd);
+	kill(pid, 9);
 
 	return 0;
 }