1

C++ プログラムで strace の出力を分析したいと考えています。アプリから起動/bin/strace psしているときに、ps から出力を取得しますが、strace からではなく、strace の出力が stdout (端末) に出力されます。パイプを使用してストリームをリダイレクトする標準的な手法を使用します。

ここに私の情報源があります:

#include <stdlib.h> 
#include <iostream> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 
#include <fcntl.h>
int main(){
    char *const parmList[] = {"/bin/strace", "ps", NULL};
    int pipes[2];
    pipe(pipes);
    pid_t child = fork();
    if(child == 0){
        close(pipes[0]);
        dup2(pipes[1],1);
        execv(parmList[0], parmList);
    }
    else{
        int status;
        wait(&status);

        fcntl(pipes[0], F_SETFL, O_NONBLOCK | O_ASYNC); 
        char buf[128] = {0}; 
        ssize_t bytesRead; 
        std::string stdOutBuf; 
        while(1) {
            bytesRead = read(pipes[0], buf, sizeof(buf)-1);
            if (bytesRead <= 0)
                break;
            buf[bytesRead] = 0;
            stdOutBuf += buf;
        } 
        std::cout << "<stdout>\n" << stdOutBuf << "\n</stdout>" << std::endl; 
    }

    close(pipes[0]);
    close(pipes[1]);

    return 0;
 }

プログラムで strace の出力を取得するにはどうすればよいですか?

4

1 に答える 1