environ #15

Merged
cromer merged 27 commits from environ into master 2021-07-17 22:15:24 -04:00
2 changed files with 17 additions and 13 deletions
Showing only changes of commit 6c3f8259e9 - Show all commits

View File

@ -23,6 +23,10 @@
*/
StringArray *create_string_array() {
StringArray *string_array = malloc(sizeof(StringArray));
if (string_array == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
string_array->array = NULL;
string_array->size = 0;
return string_array;
@ -35,25 +39,30 @@ StringArray *create_string_array() {
*/
void insert_string_array(StringArray *string_array, char *string) {
if (string_array->size == 0) {
string_array->array = malloc(sizeof(char *));
string_array->array = malloc(2 * sizeof(char *));
if (string_array->array == NULL) {
perror("malloc");
free_string_array(string_array);
exit(EXIT_FAILURE);
}
}
else {
string_array->array = realloc(string_array->array, (string_array->size + 1) * sizeof(char *));
string_array->array = realloc(string_array->array, (string_array->size + 2) * sizeof(char *));
if (string_array->array == NULL) {
perror("realloc");
free_string_array(string_array);
exit(EXIT_FAILURE);
}
}
string_array->array[string_array->size] = malloc(sizeof(string));
if (string_array->array == NULL) {
perror("malloc");
free_string_array(string_array);
exit(EXIT_FAILURE);
}
strcpy(string_array->array[string_array->size], string);
// A NULL terminated array
string_array->array[string_array->size + 1] = NULL;
string_array->size++;
}
@ -76,9 +85,10 @@ void delete_string_array(StringArray *string_array, int index) {
}
free(string_array->array[string_array->size - 1]);
string_array->array[string_array->size - 1] = NULL;
string_array->array = realloc(string_array->array, (string_array->size - 1) * sizeof(char *));
string_array->array = realloc(string_array->array, (string_array->size) * sizeof(char *));
if (string_array->array == NULL) {
perror("realloc");
free_string_array(string_array);
exit(EXIT_FAILURE);
}
string_array->size--;

View File

@ -30,18 +30,12 @@ void launch_program(StringArray *args) {
child = fork();
if (child == 0) {
// Copy the array and add a NULL to the end of it
char *argv[args->size + 1];
for (size_t i = 0; i < args->size; i++) {
argv[i] = args->array[i];
}
argv[args->size] = NULL;
execvp(args->array[0], argv);
if (execvp(args->array[0], args->array) == -1) {
fprintf(stderr, "%s: command not found\n", args->array[0]);
free_string_array(args);
exit(EXIT_FAILURE);
}
}
else if (child < 0) {
perror("fork");
}