Added kill builtin

This commit is contained in:
Gitea 2020-12-23 22:32:35 -06:00
parent 97a08b7556
commit b0604ae476

85
sh.c
View file

@ -1,4 +1,4 @@
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
@ -15,8 +15,10 @@
char** create_argv(char* command);
int get_argc(char* command);
int get_argc_argv(char * argv[]);
char* prompt();
int cd(char* path);
int _kill(int argc, char * argv[]);
int main() {
char** argv;
@ -37,6 +39,10 @@ int main() {
/* causes the fork to get skipped */
continue;
}
else if(strcmp(argv[0], "kill") == 0) {
_kill(get_argc_argv(argv), argv);
continue;
}
else if(strcmp(argv[0], "exit") == 0 ||
strcmp(argv[0], "quit") == 0) {
exit(0);
@ -135,6 +141,83 @@ int get_argc(char* command) {
return argc;
}
int get_argc_argv(char * argv[]) {
int argc = 0;
while(argv[argc] != NULL) {
argc++;
}
return argc;
}
int cd(char* path) {
return chdir(path);
}
int get_signum(char * signame) {
if(strcmp(signame, "SIGHUP") == 0) {
return 1;
}
else if(strcmp(signame, "SIGINT") == 0) {
return 2;
}
else if(strcmp(signame, "SIGQUIT") == 0) {
return 3;
}
else if(strcmp(signame, "SIGABRT") == 0) {
return 6;
}
else if(strcmp(signame, "SIGKILL") == 0) {
return 9;
}
else if(strcmp(signame, "SIGALRM") == 0) {
return 14;
}
else if(strcmp(signame, "SIGTERM") == 0) {
return 15;
}
}
int _kill(int argc, char * argv[]) {
int signal = 0; pid_t pid; char c;
int write_signame = 0, error = 0;
while((c = getopt(argc, argv, "s:l")) != -1) {
switch(c) {
case 's': signal = get_signum(optarg); break;
case 'l': write_signame = 1; break;
}
}
if(signal == 0 && argv[1][0] == '-' && write_signame == 0) {
if(argv[1][1] >= '0' && argv[1][1] <= '9') {
signal = atoi((argv[1])+1);
}
else {
signal = get_signum((argv[1])+1);
}
}
if(write_signame) {
if(argc > 2) {
/* TODO: Figure out how to get exit status from $? */
}
else {
printf("SIGHUP\n");
printf("SIGINT\n");
printf("SIGQUIT\n");
printf("SIGABRT\n");
printf("SIGKILL\n");
printf("SIGALRM\n");
printf("SIGTERM\n");
return 0;
}
}
else {
for(int i = optind; i < argc && argv[i] != NULL; i++) {
pid = atoi(argv[optind]);
if(kill(pid, signal) != 0) {
error = 1;
}
}
}
}