more defensive code

This commit is contained in:
Night Kaly 2024-02-06 18:29:16 +00:00
parent b3886e8731
commit 02fcba22d2
No known key found for this signature in database
GPG key ID: 8E829D3381CFEBBE
2 changed files with 13 additions and 5 deletions

View file

@ -47,6 +47,10 @@ int num_builtins() {
int cd(char **args) { int cd(char **args) {
if (args[1] == NULL) { if (args[1] == NULL) {
char *home = getenv("HOME"); char *home = getenv("HOME");
if (home == NULL) {
fprintf(stderr, "rush: HOME environment variable is missing\n");
exit(EXIT_FAILURE);
}
if (chdir(home) != 0) { if (chdir(home) != 0) {
perror("rush"); perror("rush");
} }
@ -171,14 +175,14 @@ int execute(char **args) {
fprintf(stderr, "rush: command not found: %s\n", args[0]); fprintf(stderr, "rush: command not found: %s\n", args[0]);
} }
} }
exit(EXIT_FAILURE); exit(EXIT_FAILURE); // exit the child
} else if (pid < 0) { } else if (pid < 0) {
perror("Cannot fork"); perror("fork failed");
} else { } else {
// Parent process // Parent process
do { while (!WIFEXITED(status) && !WIFSIGNALED(status)) {
wpid = waitpid(pid, &status, WUNTRACED); wpid = waitpid(pid, &status, WUNTRACED); // wait child to be exited to return to prompt
} while (!WIFEXITED(status) && !WIFSIGNALED(status)); }
} }
return 1; return 1;

View file

@ -17,6 +17,10 @@ void check_history_file() {
// fallback to $HOME if $XDG_CONFIG_HOME is null // fallback to $HOME if $XDG_CONFIG_HOME is null
env_home = getenv("HOME"); env_home = getenv("HOME");
} }
if (env_home == NULL) {
fprintf(stderr, "rush: HOME AND XDG_CONFIG_HOME environment variable is missing\n");
exit(EXIT_FAILURE);
}
int env_home_len = strlen(env_home); int env_home_len = strlen(env_home);
int histfilename_len = strlen(HISTFILE); int histfilename_len = strlen(HISTFILE);
int path_len = env_home_len + histfilename_len + 2; // 2 for slash and null byte int path_len = env_home_len + histfilename_len + 2; // 2 for slash and null byte