简体   繁体   English

C ++中输出顺序错误

[英]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);
}

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();

The declaration of ofstream outputFile("program3data.txt"); ofstream outputFile("program3data.txt");的声明ofstream outputFile("program3data.txt"); should occur outside the while . 外界应该发生while

Also , this program produces the output in reverse order. 同样,该程序以相反的顺序产生输出。

The order is indeterminate, execution after the fork() occurs in parallel. 顺序不确定,在fork()并行发生后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM