-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsysCommands.c
120 lines (105 loc) · 2.58 KB
/
sysCommands.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
116
117
118
119
120
#include "Header.h"
#include "sysCommands.h"
#include "customCd.h"
void add_bg(char *in_proc, int in_pid){
struct bg_prc *a = malloc(sizeof(struct bg_prc));
a = initial;
while (!(a->next == NULL || a->pid == in_pid)){
a = a->next;
}
if( a->pid == in_pid ){
strcpy(a->name,in_proc);
}
else if( a->next == NULL ){
a->size++;
a->next = malloc(sizeof(struct bg_prc));
a = a->next;
strcpy(a->name,in_proc);
a->pid = in_pid;
a->next = NULL;
}
}
char *find_bg(int in_pid){
struct bg_prc *a = malloc(sizeof(struct bg_prc));
a = initial;
while (a->pid != in_pid){
a = a->next;
}
return a->name;
}
void func(int signum){
int stat;
pid_t pid_change;
while ((pid_change = waitpid((pid_t)(-1), &stat, WNOHANG)) > 0){
char *na = find_bg(pid_change);
int exit=WEXITSTATUS(stat);
char hostname[HOST_NAME_MAX];
char username[LOGIN_NAME_MAX];
char cwd[PATH_MAX];
gethostname(hostname, HOST_NAME_MAX);
getlogin_r(username, LOGIN_NAME_MAX);
updateCwd(home_dir, cwd);
if( exit==0 ){
fprintf(stderr, "\n%s with pid %d exited normally\n", na, pid_change);
// printf("<%s@%s:%s>", username, hostname, cwd);
}
else{
fprintf(stderr, "\n%s with pid %d exited abnormally\n", na, pid_change);
// printf("<%s@%s:%s>", username, hostname, cwd);
}
fprintf(stderr, "<%s@%s:%s>", username, hostname, cwd);
// printf("<%s@%s:%s>", username, hostname, cwd);
}
}
void sysCommands(char *in_text, int bg_flag){
// remove & from command
// printf("%s\n",in_text);
if( bg_flag ){
in_text[strlen(in_text)-1] = '\0';
}
char *wordslist[1024];
int word_count = 0;
int char_count = 0;
char curr_word[1024][1024];
for(int i=0;i<=strlen(in_text);i++){
if( in_text[i]!=' ' && in_text[i]!='\0'){
while( in_text[i]!=' ' && in_text[i]!='\0'){
curr_word[word_count][char_count++] = in_text[i++];
}
curr_word[word_count][char_count] = '\0';
wordslist[word_count] = curr_word[word_count];
word_count++;
char_count = 0;
}
}
wordslist[word_count] = NULL;
int pid = fork();
if( pid<0 ){
printf("Could not create new process.\n");
return;
}
else if(pid==0){
if( bg_flag==1 ){
setpgid(0, 0);
}
if (execvp(wordslist[0], wordslist) < 0){
printf("Could not run command.\n");
exit(0);
}
}
else{
if( bg_flag==1 ){
printf("%d\n", pid);
setpgid(pid, 0);
add_bg(wordslist[0], pid);
signal(SIGCHLD, func);
return;
}
else{
int stat;
waitpid(pid, &stat, 0);
return;
}
}
return;
}