【问题标题】:Read stdout file读取标准输出文件
【发布时间】:2024-10-21 04:25:02
【问题描述】:

我已经创建了以下测试用例来模拟问题。我已经编译了源代码并能够模拟问题。

1)当系统命令时,我们得到了一些控制台(即您提交的作业),它使用 dup2 重定向到文件并创建文件 .stdout。

当我因为需要作业提交信息而尝试读取此文件时,我没有得到控制台上的数据。我能够得到我写的数据。(确认文件操作)。

我们不能从子进程创建的文件中读取控制台输出吗?

*改变rundir和cmd

#include <string>
#include <vector>
#include <utility>
#include <sstream>
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <map>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int child();
int main()
{
    string rundir = "/temp";
    pid_t id =child();
    string _xafile;
    string _afile;
    string _afilecmd;
    string line;
    stringstream ss(stringstream::in | stringstream::out);
    ss<<int(id);
    _xafile = rundir;
    _xafile = _xafile + "/" + ss.str()+".stdout";
    cout<<" _xafile is "<<_xafile<<endl;
    string cmd ="cat "+ _xafile + ">" + rundir + "/" + "process.txt";
    _afile = rundir;
    _afile = _afile + "/" + "process.txt";
    _afilecmd = "rm -rf "+ _afile;
    system(cmd.c_str());
    ifstream xafile(_afile.c_str());
     while(xafile)
        {
            string word;
            xafile >> word;
            cout<<word<<"    ";
            /* try to read console output but did not read data */
        }
    system(_afilecmd.c_str());
    return 0;
}


int child()
{
    string rundir = "/tmp";
    string cmd    = " tool <input file> -o <outputfile>";
    const char* std_out_file;
    pid_t pid = fork();
    if (pid < 0) {
    return -1;
    }
    if (pid == 0) {
    pid_t mypid = getpid();
    stringstream sm;
    sm << rundir << "/";
    if (strlen(std_out_file) == 0)
        sm << mypid << ".stdout";
    else
        sm << std_out_file;

    int fd = open(sm.str().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    dup2(fd, 1);
    dup2(fd, 2);
    int fd2 = open("/dev/zero", O_RDONLY);
    dup2(fd2, 0);
     cout<<cmd <<endl<<endl;    
  //    execl("/bin/sh", "/bin/sh", "-c", cmd, NULL);
    system(cmd.c_str());

    /*When system call it generate console output like : your job submitted */
    /* redirect to file */   
    exit(-1);
  } 

    if (pid > 0)
    return pid;

    cout<<" child is done"<<endl;
    return 0;
}

【问题讨论】:

  • 考虑修复问题中的代码缩进。顺便说一句,如果您使用编辑器的“使用空格而不是制表符”选项,您将避免这种混乱......
  • 看来你应该使用dup2之前写入标准输出。
  • 我没有得到你。它已经生成了我需要阅读的文件 processid.stdout
  • 您通常将程序/dev/null 作为标准输入,而不是/dev/zero。如果你给它/dev/zero,任何读取标准输入的进程都不会停止,因为它有无限的零字节供进程读取。你应该经常检查open-like 操作是否成功;失败后盲目向前耕作会导致问题。在使用dup()dup2() 将文件描述符复制到标准输入、标准输出或标准错误后,您几乎总是应该关闭原始文件描述符。
  • execl() 之前使用chdir() 是不寻常的;这是你想要的吗? (你有没有打印出wd的值?在你做chdir()之前进程在哪个目录?)如果execl()失败,你考虑过报错吗?它可能会帮助您确定出了什么问题。 (不过从execl()返回后退出就好了,因为返回总是意味着失败。)你打印出cmd的值了吗?

标签: c++ linux file-io operating-system


【解决方案1】:

您的想法并不完全清楚 - 您的代码似乎派生了一个子代,该子代做了一堆花哨的 io 东西来尝试将您的应用程序标准输出重定向到一个文件,然后使用 system() 运行命令。您代码中的命令有它自己的重定向,特别是通过“-o”,所以它可能没有写入标准输出。

回到父进程,您尝试打开以读取您的子进程将打开以进行写入的同一文件。你没有同步,所以它们可以以任何顺序发生。您似乎正在尝试使用“cat”来读取文件并尝试读取 cat 的标准输出?

我认为您实际上试图做的是 Perl 的 C/C++ 等价物

$foo = `ls -l /tmp`;

或类似的东西 - 执行命令并捕获输出。

更好的方法是使用管道。

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

enum { WritePipe = 1, ReadPipe = 0 };

int main(int argc, const char** argv)
{
    int pipes[2];   // each process is going to have its own file descriptor.
    if(pipe(pipes) != 0) {
        perror("pipe failed");
        return -1;
    }

    pid_t pid = fork();
    if(pid == 0) {
        // child
        close(pipes[ReadPipe]); // close the parent pipe in our context.

        // redirect stdout and stderr to the pipe.
        dup2(pipes[WritePipe], STDOUT_FILENO);
                    dup2(pipes[WritePipe], STDERR_FILENO);
                    // close(STDERR_FILENO); // <- or just do this to close stderr.

        int result = system("ls -ltr /etc");
        close(pipes[WritePipe]);
        return result;
    }

    if(pid < 0) {
        perror("fork failed");
        return -1;
    }

    // Parent process has launched the child.
    close(pipes[WritePipe]);

    char buffer[4097];
    int bytesRead;
    while((bytesRead = read(pipes[ReadPipe], buffer, sizeof(buffer) - 1)) > 0) {
        buffer[bytesRead] = 0;
        std::cout << buffer;
    }
    std::cout << std::endl;

    close(pipes[ReadPipe]);

    return 0;
}

【讨论】:

    最近更新 更多