Like a few others on here, I'm writing a basic Unix shell. Most of my commands work, including redirection, such as "ls > testfile". The problem is, after one of these redirection commands, my prompt icon disappears. If I enter some text it says "write error: Bad file descriptor", and after that is unresponsive.
After spending some time debugging, something is definitely going wrong when I attempt to close the open file descriptors. Still trying to narrow it down further but I can't get any response from close().
Code:
// File redirection example
if (strcmp(args[1], ">") == 0) {
fd = open(args[2], O_WRONLY|O_CREAT|O_TRUNC, 0644);
if (fd == -1) {
exitStatus = 1;
}
fd2 = dup2(fd, 1);
if (fd == -1) {
exitStatus = 1;
}
args[1] = NULL;
exitStatus = launch(args);
close(fd);
close(fd2);
// It never makes it to this point
}
// Job launch example
int launch(char **args) {
pid_t pid, wpid;
int status, exitStatus = 0;
pid = fork();
if (pid == 0) {
//printf("This is the child\n");
if (execvp(args[0], args) == -1) {
printf("Command not recognized\n");
exit(1);
}
} else if (pid < 0) {
perror("smallsh");
} else {
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
if (status != 0 || WIFSIGNALED(status)) exitStatus = 1;
return exitStatus;
}