1

我正在使用forktracker.stp来跟踪fork流程。脚本是这样的:

probe kprocess.create
{
  printf("%-25s: %s (%d) created %d\n",
         ctime(gettimeofday_s()), execname(), pid(), new_pid)
}

probe kprocess.exec
{
  printf("%-25s: %s (%d) is exec'ing %s\n",
         ctime(gettimeofday_s()), execname(), pid(), filename)
}

执行脚本,我发现它输出以下结果:

......
Thu Oct 22 05:09:42 2015 : virt-manager (8713) created 8713
Thu Oct 22 05:09:42 2015 : virt-manager (8713) created 8713
Thu Oct 22 05:09:42 2015 : virt-manager (8713) created 8713
Thu Oct 22 05:09:43 2015 : virt-manager (8713) created 8713
......

我不明白为什么pid()并且new_pid具有相同的价值。我怀疑它是否与“fork调用一次,返回两次”有关。所以我写了一个简单的程序来测试:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    pid_t pid;

    pid = fork();
    if (pid < 0) {
        exit(1);
    } else if (pid > 0) {
        printf("Parent exits!\n");
        exit(0);
    }

    printf("hello world\n");
    return 0;
}

跟踪这个程序,脚本输出:

Thu Oct 22 05:27:10 2015 : bash (3855) created 8955
Thu Oct 22 05:27:10 2015 : bash (8955) is exec'ing "./test"
Thu Oct 22 05:27:10 2015 : test (8955) created 8956

所以它似乎与“fork调用一次,返回两次”无关。

我如何理解pid()andnew_pid是相同的值?

4

1 回答 1

1

我认为您所看到的只是新线程,其中 pid 将相同而 tid 将不同。您可以像这样轻松地将 tid 添加到该脚本中:

probe kprocess.create {
  printf("%-25s: %s (%d:%d) created %d:%d\n",
         ctime(gettimeofday_s()), execname(), pid(), tid(), new_pid, new_tid)
}

probe kprocess.exec {
  printf("%-25s: %s (%d) is exec'ing %s\n",
         ctime(gettimeofday_s()), execname(), pid(), filename)
}

您也可以在 exec 中报告 tid,但这通常不太有趣,因为 exec 无论如何都会替换整个过程。

(这个问题也发到了邮件列表,我在这里回复了。)

于 2015-10-23T00:52:58.140 回答