-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
130 lines (110 loc) · 1.83 KB
/
shell.c
File metadata and controls
130 lines (110 loc) · 1.83 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
char *prompt(void);
char *strip_newline(char *str);
void sig_handler(int sig);
char *buf;
/**
* main - implements a super simple shell
*
* Return: 0 if successfull. 1 otherwise.
*/
int main(void)
{
char *input;
int status, child_pid;
char *argv[2];
argv[1] = NULL;
/* handle SIGINT */
if (signal(SIGINT, sig_handler) == SIG_ERR)
exit(98);
while (1)
{
/* get input */
input = prompt();
if (input == NULL)
{
write(STDOUT_FILENO, "\n", 2);
exit(0);
}
argv[0] = input;
/* create process */
child_pid = fork();
if (child_pid == -1)
{
free(input);
perror("fork Error!");
return (1);
}
else if (child_pid == 0)
{
if (execve(argv[0], argv, NULL) == -1)
{
free(input);
perror("exec Error!");
return (1);
}
}
wait(&status);
free(input);
}
return (0);
}
/**
* prompt - gets input from user
*
* Return: string containing user input. Otherwise NULL
*/
char *prompt(void)
{
size_t size = 10;
/* allocate space for buf */
buf = malloc(sizeof(char) * size);
if (buf == NULL)
return (NULL);
printf("#cisfun$ ");
/* get input */
if (getline(&buf, &size, stdin) == -1)
{
free(buf);
return (NULL);
}
/* remove newline and return */
return (strip_newline(buf));
}
/**
* strip_newline - removes newline character from a string
* @str: string
*
* Return: string with newline character stripped
*/
char *strip_newline(char *str)
{
int i;
if (str == NULL)
return (NULL);
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] == '\n')
{
str[i] = '\0';
break;
}
}
return (str);
}
/**
* sig_handler - handles SIGINT
* @sig: SIGINT
*/
void sig_handler(int sig)
{
free(buf);
(void)sig;
write(STDOUT_FILENO, "\n", 2);
exit(0);
}