Carl Peyton
Carl Peyton

Reputation: 43

Redirection in Linux with dup2() and create() inside a loop

I am running the code below and I cannot redirect to a file. The file is made, but nothing is put into it. If I remove the last dup2(saveout,1) statement, I can create and write into the file, but I cannot get back to the terminal, which is important. As soon as I put the dup2(saveout,1) back in my code, the redirection stops working, but I can get back to the terminal. I do not understand why this is happening. I would like to redirect and go back into the terminal.

main.cpp

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;

void printmessage() {
    printf("this is the message\n");
}

int main(int argc, char** argv) {    
    int saveout;
    int fd;
    saveout = dup(1);

    for (int i = 0; i < 10; i++) {
        fd = creat("/home/carl/example.txt",O_CREAT|O_APPEND);
        dup2(fd, 1);
        close(fd);
        printf("Testing the message");
        printmessage();

       dup2(saveout,1);
       close(saveout);
    }
    return 0;
}

Upvotes: 0

Views: 565

Answers (3)

jilles
jilles

Reputation: 11232

The second dup2(saveout,1); will fail because you closed saveout.

Upvotes: 0

SeedmanJ
SeedmanJ

Reputation: 444

This is a file rights issue, you should read the man pages of the functions you are using.

creat() takes as first argument the filename, and as second the file creation rights, not its opening mode.

The creat() functions is a simple open() call, with some particular flags, so that you'll just have to set up the rights.

if you want to open your file, and create it if he doesn't exists, use

open(filename, O_CREAT | O_RDWR | O_APPEND, 0600) for example, or
creat(filename, 0600),

which is mostly its equivalent, but you wont be able to append text, as "creat() is equivalent to open() with flags equal to O_CREAT | O_WRONLY | O_TRUNC"

Upvotes: 2

Dark Falcon
Dark Falcon

Reputation: 44181

printf is buffered by default. (line-by-line for output to a tty, perhaps differently for output to something else). Before both your calls to dup2(..., 1), you should flush with fflush:

fflush(stdout);

Upvotes: 0

Related Questions