dish/exec.c

63 lines
1.2 KiB
C
Raw Normal View History

2022-09-18 06:46:23 +00:00
/*
2022-09-18 15:22:20 +00:00
* @Author: 1ridic
* @Date: 2022-09-18 14:14:23
2022-09-18 06:46:23 +00:00
* @Last Modified by: 1ridic
* @Last Modified time: 2022-09-20 22:24:51
2022-09-18 06:46:23 +00:00
*/
2022-09-18 15:22:20 +00:00
#include "builtin.h"
2022-09-18 05:43:33 +00:00
#include <stdio.h>
#include <stdlib.h>
2022-09-18 06:46:23 +00:00
#include <string.h>
2022-09-18 15:22:20 +00:00
#include <sys/types.h>
#include <sys/wait.h>
2022-09-18 05:43:33 +00:00
#include <unistd.h>
2022-09-18 06:46:23 +00:00
2022-09-18 15:22:20 +00:00
extern int (*builtin_func[])(char **);
extern char *builtin_cmd[];
2022-09-18 05:43:33 +00:00
int forkExec(char **args) {
pid_t pid;
#ifdef DEBUG
2022-09-18 15:22:20 +00:00
printf("debug: fork enter.\n");
2022-09-18 05:43:33 +00:00
#endif
pid = fork();
2022-09-18 15:22:20 +00:00
if (pid == 0) {
2022-09-18 05:43:33 +00:00
/* child process */
2022-09-18 15:22:20 +00:00
if (execvp(args[0], args) == -1) {
perror("dish");
exit(EXIT_FAILURE);
}
2022-09-18 05:43:33 +00:00
} else if (pid < 0) {
/* fork error */
perror("dish");
} else {
/* parent process: wait child process*/
2022-09-18 15:22:20 +00:00
int stat_val;
waitpid(pid, &stat_val, 0);
if (WIFEXITED(stat_val)) {
return WEXITSTATUS(stat_val);
}
else if (WIFSIGNALED(stat_val)) {
return WTERMSIG(stat_val);
}
2022-09-18 05:43:33 +00:00
}
return -100;
2022-09-18 05:43:33 +00:00
}
2022-09-18 06:46:23 +00:00
int commandExec(char **args) {
int i;
if (args[0] == NULL) {
/* empty command */
return 1;
}
for (i = 0; i < getBuiltinNum(); i++) {
if (strcmp(args[0], builtin_cmd[i]) == 0) {
return (*builtin_func[i])(args);
}
}
return forkExec(args);
}