user1783628
user1783628

Reputation: 11

Wrong Order of Output in C++

I am writing a deamonizing program.Its working fine but does not produce any output in the file mentioned. Is the program I wrote for deamonizing correct? Also , this program produces the output in reverse order.Can anybody explain why?

output:

Closing File descriptors
Child Created.Exiting Parent

program :

int main(void)
{

    pid_t pid, sid;
    int i=0;
    pid = fork();
    if (pid < 0) {
            exit(EXIT_FAILURE);
    }
    if (pid > 0)
    {
            cout<<"Child Created.Exiting Parent\n";
            exit(EXIT_SUCCESS);
    }
    umask(0);
    sid = setsid();
    if (sid < 0)
    {
            exit(EXIT_FAILURE);
    }
    if ((chdir("/home/csgrad/suryakum/checking")) < 0)
    {
          cout<<"Directory not changed\n";
          exit(EXIT_FAILURE);
    }
    cout<<"Closing File descriptors\n";
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    while (1)
    {
            i++;
            ofstream outputFile("program3data.txt");
            outputFile<< "Run "<<i<<"\n";
            sleep(30); /* wait 30 seconds */
    }
    exit(EXIT_SUCCESS);
}

Upvotes: 1

Views: 720

Answers (2)

birubisht
birubisht

Reputation: 908

one of the basic thing in file handling that you are missing here is whenever we will open a stream to write in a file we must have to close that stream. add the follwing line after writing to the file .

outputFile.close();

Upvotes: 1

Brian Cain
Brian Cain

Reputation: 14619

The declaration of ofstream outputFile("program3data.txt"); should occur outside the while.

Also , this program produces the output in reverse order.

The order is indeterminate, execution after the fork() occurs in parallel.

Upvotes: 0

Related Questions