loop #2

Merged
cromer merged 11 commits from loop into master 2021-06-19 23:03:40 -04:00
5 changed files with 39 additions and 3 deletions
Showing only changes of commit 93ace63885 - Show all commits

View File

@ -2,7 +2,7 @@ CC=clang
CFLAGS=-Wall -Isrc/include -DDEBUG -g -std=c17 CFLAGS=-Wall -Isrc/include -DDEBUG -g -std=c17
LDFLAGS= LDFLAGS=
FILENAME=myshellin FILENAME=myshellin
SRC=src/myshellin.c src/loop.c SRC=src/myshellin.c src/loop.c src/user.c
OBJ=$(SRC:.c=.o) OBJ=$(SRC:.c=.o)
all: myshellin all: myshellin

View File

@ -1,2 +1,3 @@
void remove_new_line(char *line);
void print_input_line(); void print_input_line();
void loop(); void loop();

1
src/include/user.h Normal file
View File

@ -0,0 +1 @@
char *get_user();

View File

@ -1,10 +1,18 @@
#define _GNU_SOURCE #define _GNU_SOURCE
#include <errno.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <sys/types.h> #include <sys/types.h>
#include "user.h"
void remove_new_line(char* line) {
line[strcspn(line, "\n")] = 0;
}
void print_input_line() { void print_input_line() {
printf("$ "); char *name = get_user();
printf("%s $ ", name);
} }
void loop() { void loop() {
@ -13,6 +21,23 @@ void loop() {
while (1) { while (1) {
print_input_line(); print_input_line();
getline(&line, &buffer_size, stdin); if (getline(&line, &buffer_size, stdin) == -1) {
if (feof(stdin)) {
// the stdin was closed, this usually happens for CTRL-D
printf("\n");
exit(EXIT_SUCCESS);
}
else {
perror("Error: ");
printf("\n");
exit(EXIT_FAILURE);
}
}
remove_new_line(line);
if (strcmp(line, "quit") == 0) {
break;
}
} }
} }

9
src/user.c Normal file
View File

@ -0,0 +1,9 @@
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
char *get_user() {
struct passwd *pass;
pass = getpwuid(getuid());
return pass->pw_name;
}