c++ - C++ 中错误的输出顺序

标签 c++

我正在编写一个 deamonizing 程序。它工作正常但不会在提到的文件中产生任何输出。我写的去魔化程序对吗?此外,该程序以相反的顺序生成输出。任何人都可以解释为什么吗?

输出:

Closing File descriptors
Child Created.Exiting Parent

程序:

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

最佳答案

您在这里缺少的文件处理的基本内容之一是,每当我们打开流以写入文件时,我们必须关闭该流。 写入文件后添加以下行。

outputFile.close();

关于c++ - C++ 中错误的输出顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126756/

相关文章:

c++ - 不寻常的范围解析运算符

c++ - 处理许多 GPIO 中断 C++ Linux

c++ - 错误消息 "invalid conversion from ‘void*’ 到 ‘unsigned int’“

c++ - 在具有 std::pair 键和值的映射中添加 b2vec2

c++ - 您如何在 (windows) tagVARIANT 中存储字符串?

c++ - 如何在 C++ 中进行快速字符串连接

c++ - 特质专精

c++ - Microsoft 的源注释语言 (SAL)——有什么方法可以利用它?

c++ - 如果添加了虚函数,Build是否需要依赖DLL

c++ - 使用 boost::asio poll 避免忙等待