diff options
author | Niklas Halle <niklas@niklashalle.net> | 2020-06-06 14:06:00 +0200 |
---|---|---|
committer | Niklas Halle <niklas@niklashalle.net> | 2020-06-06 14:06:00 +0200 |
commit | e1520589de17d08c4bde37f1198f18d012a1f377 (patch) | |
tree | b4a0f93466c9c53688bad02c69d39d409d23ce5b /03_exercise/cli/client.c | |
parent | 74abc79434fe895d0ca863e4d1d6c5c16b54f296 (diff) | |
download | betriebssysteme-e1520589de17d08c4bde37f1198f18d012a1f377.tar.gz betriebssysteme-e1520589de17d08c4bde37f1198f18d012a1f377.zip |
basic shell works - sometimes goes out of sync (running current command only after issueing the next)
Diffstat (limited to '03_exercise/cli/client.c')
-rw-r--r-- | 03_exercise/cli/client.c | 39 |
1 files changed, 30 insertions, 9 deletions
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 <stdlib.h> #include <unistd.h> +#include <fcntl.h> +#include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> @@ -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; |