Reputation: 65
This program is supposed to be shell which executes commands entered by the user. My program worked fine until I made it accept flags as well as commands. Now, the program loops infinitely at execvp. Any command entered will do this(I've primarily been testing with ls -l). If it matters, I'm writing this code on a Linux machine using the cc compiler. Here is my current code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<linux/types.h>
#define MAX_LINE 80
int main(void)
{
char *args[MAX_LINE/2+1];
char buffer[80];
char *token=NULL;
char *whiteSpace = " \t\n\f\r\v";
while(1)
{
fflush(stdout);
printf("osh> ");
fflush(stdout);
scanf("%[^\n]",buffer);
int count=0;
token=strtok(buffer,whiteSpace);
args[count] = strdup(token);
count+=1;
while((token=strtok(NULL,whiteSpace))!=NULL)
{
args[count]=strdup(token);
count+=1;
}
args[count]=NULL;
pid_t pid = fork();
if(pid==0)
{
if((execvp(args[0],args))==-1)
{
printf("Error\n");
exit(1);
}
} else if(pid>0) {
if(args[count-1]=="&")
wait();
else
waitpid(pid,0,0);
} else {
exit(1);
}
}
return 0;
}
Any help or direction is greatly appreciated
Upvotes: 0
Views: 1139
Reputation: 681
In the scanf function repeatedly \n
will be running so you have to use following
scanf(" %[^\n]",buffer);
Upvotes: 0
Reputation: 4041
After getting the first input you are not clearing the input buffer. so this is the reason for the infinite loop.
After entering the first input new line will be there in input
buffer. After processing first input then buffer will give the \n
.
scanf("%[^\n]",buffer); // This scanf will not get the input.
So buffer
will contain the first command user gave. so it will process with that input.
Make this line end of the while
loop or after the scanf
.
Declare the variable int c;
while((c=getchar()) != '\n' && c != EOF);// for clearing the buffer until newline or End-Of-File character.
Or else you can use like this,
scanf(" %[^\n]",buffer); // to skip the white space character.
^
|
Upvotes: 1