jasimp
jasimp

Reputation: 73

Global variable not staying set, maybe caused by fork()

I'm trying to write a very very simple unix shell in C, and I have the basics of what I need working, except support for a history command. I have a global 2D char array that holds the history of all entered commands. Commands are added before the fork() system call, and I was originally printing out the value of the history global array after strings were added, and they were printing out correctly, so I'm not sure why it doesn't print out when the command "history" is used at the shell.

Thank to anyone who takes a look.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "myhistory.h"

int BUFFER_SIZE = 1024;
char history[100][80];

int command_index = 0;

int main(int argc, char *argv[]){

int status = 0;
int num_args;
pid_t pid;

while(1){

    char *buffer_input, *full_input;
    char command[BUFFER_SIZE];
    char *args[BUFFER_SIZE];

    printf("myshell> ");
    buffer_input = fgets(command, 1024, stdin);

    full_input = malloc(strlen(buffer_input)+1);
    strcpy(full_input, buffer_input);


    if (command_index >= 100) {
        command_index = 0;
    }

    strncpy(history[command_index], full_input, strlen(full_input) + 1);
    command_index += 1;

    parse_input(command, args, BUFFER_SIZE, &num_args);


    //check exit and special command conditions
    if (num_args==0)
        continue;

    if (!strcmp(command, "quit" )){
        exit(0);
    }

    if(!strcmp(command, "history")){
        int i;
        fprintf(stderr,"%d\n",(int)pid);
        for(i = 0; i < command_index; i++){
            fprintf(stdout, "%d: %s\n",i+1,history[command_index]);
        }

        continue;
    }

    errno = 0;
    pid = fork();
    if(errno != 0){
        perror("Error in fork()");
    }
    if (pid) {
        pid = wait(&status);
    } else {

        if( execvp(args[0], args)) {
            perror("executing command failed");
            exit(1);
        }
    }
}
return 0;
}


void parse_input(char *input, char** args,
            int args_size, int *nargs){

    char *buffer[BUFFER_SIZE];
    buffer[0] = input;

    int i = 0;
    while((buffer[i] = strtok(buffer[i], " \n\t")) != NULL){
        i++;
    }

    for(i = 0; buffer[i] != NULL; i++){
        args[i] = buffer[i];
    }
    *nargs = i;
    args[i] = NULL;
}

Upvotes: 0

Views: 100

Answers (1)

Barmar
Barmar

Reputation: 780851

Change:

        fprintf(stdout, "%d: %s\n",i+1,history[command_index]);

to:

        fprintf(stdout, "%d: %s\n",i+1,history[i]);

Upvotes: 1

Related Questions