-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmsh_utils.c
115 lines (100 loc) · 2.49 KB
/
msh_utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "shell.h"
/**
* init_shell - initializes shell data
*
* Return: shell data initialized
*/
shell_t *init_shell(void)
{
shell_t *msh = malloc(sizeof(shell_t));
if (msh == NULL)
{
fprintf(stderr, "Launching shell failed.\n"
"Please ensure you have enough system resources for this operation\n");
exit(-1);
}
msh->path_list = NULL;
msh->aliases = NULL;
msh->line = NULL;
msh->sub_command = NULL;
msh->commands = NULL;
msh->tokens = NULL;
msh->token = NULL;
msh->cmd_count = 0;
msh->exit_code = 0;
return (msh);
}
/**
* get_hostname - returns the hostname of the system using the '/ect/hostname'
* file
* @buffer: the buffer to write the hostname to, it should large enough.
*
* Return: the hostname if found, else defaults to using 'msh' when anything
* goes wrong
*/
char *get_hostname(char *buffer)
{
int fd, n_read;
fd = open("/etc/hostname", O_RDONLY);
/* let's check whether the file opening failed */
if (fd == -1)
{
/* looks like it did, fall back to using 'msh' as the hostname */
_strcpy(buffer, "msh");
return (buffer);
}
/* file opening was successful, let's grab the hostname */
n_read = read(fd, buffer, 100);
/* one more time, let's check for read failures and fall back as needed */
if (n_read == -1 || n_read == 0)
_strcpy(buffer, "msh");
else
buffer[n_read - 1] = '\0'; /* hostname was succesfully grabbed, use it */
close(fd);
return (buffer);
}
/**
* show_prompt - shows the prompt in interactive mode
*/
void show_prompt(void)
{
char prompt[PROMPT_SIZE], hostname[100];
char *username = _getenv("USER"), *pwd;
if (username != NULL)
{
pwd = _getenv("PWD");
if (pwd != NULL)
{
/* get the right directory name to show on the prompt */
pwd = (*pwd == '/' && *(pwd + 1) == '\0')
? pwd
: (_strrchr(pwd, '/') +
1); /* show only the current directory */
sprintf(prompt, "[%s@%s %s]%% ", username, get_hostname(hostname),
(!_strcmp(pwd, username))
? "~" /* show '~' for the user's $HOME directory */
: pwd);
}
}
else
{
/*
* there was not enough environment variables to build a much more
* customized prompt, fall back to the minimal prompt
*/
sprintf(prompt, "msh%% ");
}
/* show the prompt in interactive modes only */
if (isatty(STDIN_FILENO))
printf("%s", prompt);
}
/**
* sigint_handler - handles signal interrupts (Ctrl+C)
* @signum: signal number (unused)
*/
void sigint_handler(__attribute__((unused))int signum)
{
putchar('\n');
show_prompt();
fflush(stdout);
}