J
jorntk
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
/*limit the lenght of input to 256 character and number
of argument to 10*/
#define MAX 256
#define CMAX 10
char logout[]= "logout";
int spawn(char* program, char** arg_list)
{
pid_t child_pid;
if(!strcmp(program,logout))
{
exit(0);
}
if ((child_pid=fork())==0)
{
execvp(program,arg_list);
perror("execvp");
exit(1);
}
}
int main()
{
char input[MAX];
char *p;
char *arg_list[CMAX+1];
int i;
while(1)
{
printf("Shell> ");
if (fgets(input,sizeof input, stdin)!=NULL)
{
if(strchr(input,'\n'))
*strchr(input,'\n')=0;
else
{
while (!strchr(input,'\n'))
fgets(input, sizeof input,stdin);
exit(1);
}
}
p=strtok(input," ");
for(i=0;i<CMAX;++i)
{
arg_list=p;
p=strtok(NULL," ");
}
arg_list=0;
spawn(arg_list[0], arg_list);
}
return 0;
}
the above program can accept commnand from user and execute it, i need
advice on how to expand its function to include pipe function. other
thing is where should i place code to exit when logout is enter, i
have try checking in spawn process it works but the program will
return segmentation error when click enter with not other command.
thanks in advance.
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
/*limit the lenght of input to 256 character and number
of argument to 10*/
#define MAX 256
#define CMAX 10
char logout[]= "logout";
int spawn(char* program, char** arg_list)
{
pid_t child_pid;
if(!strcmp(program,logout))
{
exit(0);
}
if ((child_pid=fork())==0)
{
execvp(program,arg_list);
perror("execvp");
exit(1);
}
}
int main()
{
char input[MAX];
char *p;
char *arg_list[CMAX+1];
int i;
while(1)
{
printf("Shell> ");
if (fgets(input,sizeof input, stdin)!=NULL)
{
if(strchr(input,'\n'))
*strchr(input,'\n')=0;
else
{
while (!strchr(input,'\n'))
fgets(input, sizeof input,stdin);
exit(1);
}
}
p=strtok(input," ");
for(i=0;i<CMAX;++i)
{
arg_list=p;
p=strtok(NULL," ");
}
arg_list=0;
spawn(arg_list[0], arg_list);
}
return 0;
}
the above program can accept commnand from user and execute it, i need
advice on how to expand its function to include pipe function. other
thing is where should i place code to exit when logout is enter, i
have try checking in spawn process it works but the program will
return segmentation error when click enter with not other command.
thanks in advance.