loop #2
2
Makefile
2
Makefile
@ -2,7 +2,7 @@ CC=clang
|
||||
CFLAGS=-Wall -Isrc/include -DDEBUG -g -std=c17
|
||||
LDFLAGS=
|
||||
FILENAME=myshellin
|
||||
SRC=src/myshellin.c src/loop.c
|
||||
SRC=src/myshellin.c src/loop.c src/user.c
|
||||
OBJ=$(SRC:.c=.o)
|
||||
|
||||
all: myshellin
|
||||
|
@ -1,2 +1,3 @@
|
||||
void remove_new_line(char *line);
|
||||
void print_input_line();
|
||||
void loop();
|
||||
|
1
src/include/user.h
Normal file
1
src/include/user.h
Normal file
@ -0,0 +1 @@
|
||||
char *get_user();
|
29
src/loop.c
29
src/loop.c
@ -1,10 +1,18 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include "user.h"
|
||||
|
||||
void remove_new_line(char* line) {
|
||||
line[strcspn(line, "\n")] = 0;
|
||||
}
|
||||
|
||||
void print_input_line() {
|
||||
printf("$ ");
|
||||
char *name = get_user();
|
||||
printf("%s $ ", name);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
@ -13,6 +21,23 @@ void loop() {
|
||||
|
||||
while (1) {
|
||||
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
9
src/user.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user