I have made a shell that accept a command and parameters. It is working properly. I have tryed to implement background process in main(). But i dont know to implement them. Can anyone give me a lille example??
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* The following define's belongs to read_command(..) */
#define MAXPARMS 20
#define MAXPARMLEN 255
#define MAXINPUT 255
#define shell "cesh"
/* The Command line parser */
/*------------------------------------------------------------------*/
/* read_command: */
/* Print the prompt and get one characters from the users which */
/* makes up an entire command line entry */
/*------------------------------------------------------------------*/
void read_command(char * command, char * parameters[])
{
char input[MAXINPUT];
char * parm;
char c;
int i;
/* initialize the whole parameters array to NULL pointers */
for (i=0;i<MAXPARMS;i++)
{
parameters=NULL;
}
i=0;
input[0]='\0';
/* loop until some characters are entered on the command line */
do
{
printf("%s> ", shell);
c=getchar();
while ((c != '\n') && (i < MAXINPUT-1))
{
input=c;
i++;
c=getchar();
}
input='\0';
} while (strlen(input)==0);
/* copy the first "word" on the command line into the command var */
/* this also initializes the use of the strtok function */
strcpy(command, strtok(input, " "));
parameters[0]=malloc((MAXPARMLEN+1)*sizeof(char));
strcpy(parameters[0], command);
i=1;
/* separate all of the "words" on the command line. Each becomes */
/* a string pointed to by the parameters array using strtok. */
do
{
if (parm=strtok(NULL, " "))
{
parameters=malloc((MAXPARMLEN+1)*sizeof(char));
strcpy(parameters,parm);
}
else
{
parameters=NULL;
}
i++;
} while((parameters[i-1]!=NULL) && (i < MAXPARMS));
return;
}
int main(void)
{
char name[10];
char *argv[MAXPARMS];
read_command(name, argv);
/*background process*/
int pid, status;
int BGRND = 0;
do
{
if (strcmp(argv[0], "&")==0))
{
BGRND = 1;
}
if ( (pid = fork() < 0 )
return 0;
if(pid == 0 )
{
if ((execvp(argv[0], argv)) == -1)
printf("%s: Command not found.\n", tokenstr);
return 0;
}
if(BGRND == 0)
{
while (waitpid(-1, &status, 0) != pid);
}
BGRND = 0;
}while(strcmp(name,"exit));
return 0;
}