Thread: stdout redirection and re-control

  1. #1
    Registered User
    Join Date
    Mar 2009
    Location
    Bozen
    Posts
    95

    stdout redirection and re-control

    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?

  2. #2
    Registered User
    Join Date
    Mar 2009
    Location
    Bozen
    Posts
    95
    anyone with help on this?

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I think the answer to your question is that you have to dup2 back the original "stdin" handle.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed