EDIT: I've managed to narrow down the problem, but it still doesn't make much sense to me. My code becomes 8 lines:
int savedOut = dup(1);
printf("Changing the outstream to process.txt!")
if ( freopen("process.txt", "w"m stdout) == NULL)
printf("FREOPEN() FAILURE")
printf("Print to File\n");
dup2(savedOut, 1);
printf("Done with print to file");
return 1;
This code prints all to the terminal. Removing the two lines with "savedOut" prints all to process.txt. I understand the latter result, but I don't understand the former.
END EDIT
I'm having a lot of difficulty working with freopen()
. Take this snippet of code:
int savedIn = dup(0);
int savedOut = dup(1);
while(1)
{
readFile[0] = '\0';
writeFile[0] = '\0';
dup2(savedIn, 0);
dup2(savedOut, 1);
if(getInputFlag == 1)
{
printf("myshell$ ");
gotInputFlag = getUserInput(arguments, command, readFile, writeFile, catOrApp, bkgdFlag);
}
else
{
gotInputFlag = getUserInput(arguments, command, readFile, writeFile, catOrApp, bkgdFlag);
}
if(gotInputFlag == 1)
{
history[historySize] = (char*)malloc(sizeof(char) * 1000);
if (writeFile[0] != '\0' && *catOrApp == 0)
{
printf("Changing the outstream!\n");
freopen(writeFile, "w", stdout);
}
printf("Print to File\n");
dup2(savedIn, 0);
dup2(savedOut, 1);
printf("Done with print to file!\n");
...
This program will execute and print "Changing the Outstream!" just as expected. "Print to File!" is never printed, neither to the terminal nor to the writeFile. "Done with print to file!\n" does not print either. Later on in the code, the code calls an execv()
on a Hello World program, which prints to terminal as expected. However, upon program termination suddenly all the printf statements print to terminal, even the "Print to File" statements.
Save for a single fgets()
, getUserInput()
does not work with streams.
I can't for the life of me understand why this is happening. Does anyone have any idea?