[英]How to capture output of strace in C++ program
I want to analyse the output of strace in my C++ program. 我想在我的C ++程序中分析strace的输出。 While launching
/bin/strace ps
from my app I get an output from ps, but not from strace and strace output is printed to stdout (my terminal). 从我的应用程序启动
/bin/strace ps
,我从ps获得了输出,但没有从strace获得,并且strace的输出被打印到stdout(我的终端)。 I use standard technique of using pipes and redirecting streams. 我使用使用管道和重定向流的标准技术。
Here is my source: 这是我的资料来源:
#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;
}
How can I get an output of strace in my program? 如何在程序中获得strace的输出?
strace writes to stderr
not to stdout
, if you only want to capture the strace output just use stderr instead of stdout strace写入
stderr
而不是stdout
,如果您只想捕获strace输出,只需使用stderr而不是stdout
change the dup2
line like this 像这样更改
dup2
行
dup2(pipes[1],2);
If you want combined strace and ps output do this: 如果要结合使用strace和ps输出,请执行以下操作:
dup2(pipes[1],1);
dup2(pipes[1],2);
if you want separated output you'll probably need to use non-blocking reads and select() or poll() 如果要分离输出,则可能需要使用非阻塞读取和select()或poll()
Also: after calling exec you should print an error message, if everything works exec won't return, but if something goes wrong with the exec, it's good to know. 另外:在调用exec之后,您应该打印一条错误消息,如果一切正常,exec不会返回,但是如果exec出了点问题,很高兴知道。
std::cerr << "exec failed!";
I used this code and had success: 我使用此代码并获得成功:
#include <stdlib.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
char *const parmList[] = {"/usr/bin/strace", "ps", NULL};
int pipes[2];
pipe(pipes);
pid_t child = fork();
if(child == 0){
close(pipes[0]);
dup2(pipes[1],2);
execv(parmList[0], parmList);
std::cerr << "exec fail\n" ;
}
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;
}
HTH HTH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.