Hello,
I'm encountering a strange behaviour in my shell when I try to redirect standard output. All I do is open a file with open(), dup2(), and then close() and return. Yet this series of calls strangely doesn't return standard output to the shell but remains in the file (although command returns to the shell).
Here is the responsible code:
Code:
if (strncmp(args[0], "out",3) == 0){
if ((file_desc = open(args[1], O_CREAT | O_TRUNC | O_WRONLY | O_APPEND, S_IWRITE)) == -1) {
printf("Cannot open the file %s.\n", args[1]);
fflush(stdout);
return;
}
if (dup2(file_desc, STDOUT_FILENO) == -1){
printf("Cannot duplicate file descriptor %d.\n", file_desc);
fflush(stdout);
return;
}
if (close(file_desc) == -1) fprintf(stderr, "err");
parseFile(args, &argc, &fileName, false);
fprintf(stderr, "stdout redirected to %s.\n", fileName);
// exe(args, bg, fileName);
return;
}
Disregard parseFile and exe as they should have no effect. Please advise what I might be doing wrong.
Also, how could I explicitly set the stdout to be the default one again, if that solves it?