From e1520589de17d08c4bde37f1198f18d012a1f377 Mon Sep 17 00:00:00 2001 From: Niklas Halle Date: Sat, 6 Jun 2020 14:06:00 +0200 Subject: basic shell works - sometimes goes out of sync (running current command only after issueing the next) --- 03_exercise/cli/client | Bin 23056 -> 23640 bytes 03_exercise/cli/client.c | 39 ++++++++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 9 deletions(-) (limited to '03_exercise/cli') diff --git a/03_exercise/cli/client b/03_exercise/cli/client index 53ba0d8..c57cade 100755 Binary files a/03_exercise/cli/client and b/03_exercise/cli/client differ diff --git a/03_exercise/cli/client.c b/03_exercise/cli/client.c index 527c67c..83b4dec 100644 --- a/03_exercise/cli/client.c +++ b/03_exercise/cli/client.c @@ -3,6 +3,8 @@ #include #include +#include +#include #include #include #include @@ -10,7 +12,21 @@ #define PORT 9000 #define HOST "127.0.0.1" -#define BUF_SIZE 1024 +#define BUF_SIZE 2048 + +int cfd; + +/* Signal Handler for SIGINT */ +void sigintHandler(int sig_num) { + errno = 0; + if (fcntl(cfd, F_GETFD) != -1 || errno != EBADF) { + write(cfd, "exit\n", 6); + close(cfd); + } + printf("Terminating client\n"); + fflush(stdout); + exit(-1); +} static inline void die(const char *msg) { perror(msg); @@ -23,8 +39,7 @@ int main() { .sin_port = htons(PORT), .sin_addr.s_addr = inet_addr(HOST) }; - char buf[BUF_SIZE]; - int cfd; + char buf[BUF_SIZE]; if ((cfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) die("Could not open socket"); @@ -36,8 +51,14 @@ int main() { size_t cap = 0; __ssize_t length; + if (read(cfd, buf, BUF_SIZE) < 0) + die("Could not receive message"); + + printf("%s\n$> ", buf); + memset(buf, 0, BUF_SIZE); + while (1) { - printf("%s > ", HOST); + //printf("[C] awaiting command\n"); if ((length = getline(&line, &cap, stdin)) < 0) { fprintf(stderr, "Failed to read from STDIN"); fflush(stderr); @@ -49,14 +70,14 @@ int main() { continue; } - line[length - 1] = '\0'; // cut the line feed + strncpy(buf, line, strlen(line) + 1); - strncpy(buf, line, strlen(line)); + //printf("[C] pre send: \"%s\"\n", buf); - if (write(cfd, buf, BUF_SIZE) < 0) + if (write(cfd, buf, strlen(line)) < 0) die("Could not send message"); - if (strcmp(line, "exit") == 0) { + if (strcmp(line, "exit\n") == 0) { free(line); line = NULL; break; @@ -65,7 +86,7 @@ int main() { if (read(cfd, buf, BUF_SIZE) < 0) die("Could not receive message"); - printf("%s\n", buf); + printf("%s$> ", buf); memset(buf, 0, BUF_SIZE); free(line); line = NULL; -- cgit v1.2.3-54-g00ecf