The child now remains open after the parents closes, but I noticed that in a loop, the child still dies if the parent is killed via ctrl-c.
How can I keep the child alive regardless of how the parent is killed?
Code:
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
/* Compile and run with:
gcc -Wall run.c -o run -lncursesw && run
*/
void handler(int signum) {
write(STDOUT_FILENO, "\nExiting gracefully.", 20);
printf("\n");
exit(1);
}
void execute(char **arg) {
pid_t pid;
int exec;
if ((pid = fork()) < 0) {
exit(1);
} else if (pid == 0) {
exec = execvp(*arg, arg);
if (exec < 0)
exit(1);
} else {
//while (waitpid(-1, NULL, WNOHANG) != pid);
}
}
#define MAX_LINE 256
int main(int argc, char* argv[], char*envp[]) {
char text[MAX_LINE];
char *args[MAX_LINE/2 + 1]; // Calculate max elements possible
signal(SIGINT, handler);
signal(SIGKILL, handler);
signal(SIGTERM, handler);
do {
printf("\nShell: ");
fgets(text, MAX_LINE, stdin);
text[strlen(text) - 1] = '\0'; // strip return carriage at end of text
args[0] = strtok(text, " ");
for (int i = 0; args[i] != NULL; )
args[++i] = strtok(NULL, "\"' " ); // consider quotations too
execute(args);
} while (strcmp(text, "exit") != 0);
return 0;
}