I want to execute multiple commands like ./shell ls > test.txt;ls > test1.txt;ls > test2.txt;
which should print the output 3 times in mentioned files. However, somehow my code only prints once.
I have separated char buffer by ';' using strtok_r.
Also, I had a look the other example which is similar to my problem: Nested strtok function problem in C
This is my code
void call_system(char *argv[],int argc)
{
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = child_handler;
sigaction(SIGCHLD, &sa, NULL);
int pid;
int background;
/*two process are created*/
pid=fork();
background = 0;
if(pid<0)
{
fprintf(stderr,"unsuccessful fork /n");
exit(EXIT_SUCCESS);
}
else if(pid==0)
{
chdir("h/Ravi Griffith/Sem 1-2015/SP/Assignment1/Assignment1");
char *bname;
char *path2 = strdup(*argv);
bname = basename(path2);
execvp(bname, argv);
}
else if(pid>0)
{
/*it will wait untill the child process doesn't finish*/
child_handler(pid);
exit(EXIT_SUCCESS);
}
}
int main(int argc,char *argv[])
{
if(argc>1)
{
/*it will check whether a user has entered exit then the code will be executed successfully.*/
if(strcmp( argv[1], "exit")==0)
{
exit(EXIT_SUCCESS);
}
}
else
{
printf("Enter Shell Command -- ");
char buffer[80];
fgets(buffer, sizeof(buffer), stdin);
//it will replace the newline character with null
buffer[strlen(buffer) - 1] = '\0';
char *end_str;
char* token= strtok_r(buffer, ";", &end_str);
/* string will be split in individual argument array */
while(token != NULL)
{
int i;
char *endtoken;
printf("a = %s\n", token);
char *array[strlen(buffer)];
i = 0;
char *token2 = strtok_r(token," ", &endtoken);
while (token2 != NULL)
{
array[i++] = token2;
token2 = strtok_r(NULL, " ", &endtoken);
}
if(sizeof(array)>16)
{
char *arrow=array[strlen(buffer)-1];
char *filename;
filename=array[strlen(buffer)];
/*printf("%s",arrow);
printf("%s",filename);*/
if(strcmp( arrow, ">") == 0)
{
freopen( filename, "w", stdout );
}
else if(strcmp( arrow, "<") == 0)
{
freopen( filename, "rb", stdin );
}
}
splittoarray(buffer,argv);
call_system(argv,argc);
token = strtok_r(NULL, ";",&end_str);
}
}
}