Hi, I wrote the following code which creates a simple shell (like bash). It works fine, can take a command along with arguments and run it or give error if it doesn't exist. However, the strange problem is that it doesn;t execute anything the first time "enter" is hit!! But after that it works perfectly.
I couldn't find the bug, any help would be great. Thanks
---------------------------------------------------------------------------------------------
Code:
#include <string.h>
#include <errno.h>
#define TRUE 1
void type_prompt();
void *read_command(char *argv[]);
int n = 0;
int main(int argc, char *argv[], char *envp[])
{
char *command;
int status;
argv[0] = NULL;
while (TRUE) /* repeat forever */
{
type_prompt(); /* display prompt on screen */
read_command(argv); /* read input from terminal */
if (fork() != 0) /* fork off child process */
{
waitpid(-1, &status, 0); /* wait for child to exit */
}
else
{
if (execve(argv[0], argv, envp) == -1) /* execute command */
printf("Ouch, can't execute: %s\n", strerror(errno));
}
}
return 0;
}
void type_prompt()
{
printf("[arajgarh]$ ");
}
void *read_command(char *argv[])
{
n = 0;
char temp[256];
gets(temp);
argv[n++] = strtok (temp," ");
while (argv[n-1] != NULL)
argv[n++] = strtok (NULL, " ");
}