我试图找出一种通过其子进程在C中分析进程的方法,片刻后父进程杀死其子进程以停止分析。我正在使用perf来分析我的应用程序。perf被杀死后将在文件中输出结果。在bash脚本中看起来像这样:
./run &
perf stat -o perf.data -p <pid_run> &
kill -9 <pid_perf>
到目前为止,我所做的是:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
static pid_t perf_id;
void start() {
char *filename="test_data";
char ppid_str[24];
pid_t pid = fork();
if (pid == 0){
pid_t ppid = getppid();
sprintf(ppid_str, "%d",ppid);
char *args[] = {"/usr/bin/perf", "stat","-p",ppid_str,"-o", filename, NULL};
execvp(args[0], args);
}
else {
perf_id = pid
}
}
void stop() {
kill(perf_id,SIGKILL);
}
我在获取perf的输出时遇到问题。这是可以运行父进程的代码示例:
int main() {
start();
int a = 0;
a+=1;
stop();
// ... // There are other instructions after the stop
return 0;
}
运行此代码时,我没有从perf获得任何输出。我必须杀死父进程才能获得输出。
如果我在杀死子进程之前进行了睡眠调用,则程序将输出一个空文件。
编辑:
stat参数是命令中的一个示例,我也想使用record参数
如Zulan所述,如果我使用SIGINT
代替SIGKILL
,我将得到一个输出,但是只有在主进程睡眠1秒钟时我才能得到一个输出。
您应该发送aSIGINT
而不是aSIGKILL
以便perf
完全关闭并生成有效的输出文件。perf
子进程与主进程之间的同步仍将是不完美的-因此,如果主进程不需要花费您的示例中的大量时间,则很可能根本不生成任何输出文件。这也会影响所收集数据的准确性。通过使用perf
作为子进程而不是反之的设置,您无法真正改善它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句