When i run the program with the ls > filename
command it prints the results in the file but after that it doesn't respond to other commands like ls
etc . Here is the code :
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
void execute(char **argv, char ** k, int *l)
{
pid_t pid;
int file_descriptor;
int status;
int file;
if ((pid = fork()) < 0)
{
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0)
{
if (l = 1)
{
file = open(k, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
file_descriptor = dup2(file, 1);
}
if (execvp(argv[0], argv) < 0)
{
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else
{
while (wait(&status) != pid)
;
}
}
void main(void)
{
char **name = (char**) malloc(256 * sizeof(char));
char line[1024];
char ** k;
int file;
int i;
int *l;
while (1)
{
l = 0;
i = 0;
printf("myShell3 -> ");
gets(line); // gets the input command from user
printf("\n");
name[i] = strtok(line, " ");
while (name[i] != NULL)
{
if (strcmp(name[i], ">") == 0)
{
i++;
l = 1;
k = strtok(NULL, " ");
name[i - 1] = name[i];
}
else if (!strcmp(name[i], "<"))
{
i++;
name[i] = strtok(NULL, " ");
name[i - 1] = name[i];
}
else
{
i++;
name[i] = strtok(NULL, " ");
}
}
execute(name, k, l);
}
}
I have spent many hours on how to fix this but didnt find solution . Any help would be very much appreciated