努力附加到多线程进程

问题描述 投票:26回答:2

如果我想要一个多线程进程(所有线程),我应该怎么做?

我知道可以做strace -f跟随分叉进程吗?但是当我开始打算时,如何附加到已经是多线程的进程呢?是一种告诉strace跟踪属于该进程的所有线程的所有系统调用的方法吗?

linux strace
2个回答
22
投票

我只是通过列出要跟踪的每个tid以一种kludgy方式做到这一点。

你可以通过ps找到它们:

$ ps auxw -T | fgrep program_to_trace
me pid tid1 ...
me pid tid2 ...
me pid tid3 ...
me pid tid4 ...

然后,根据man strace,您可以同时附加到多个pid:

   -p pid      Attach to the process with the process ID pid and begin tracing.  The trace may be terminated at any time by a  keyboard  interrupt
               signal  (CTRL-C).  strace will respond by detaching itself from the traced process(es) leaving it (them) to continue running.  Mul‐
               tiple -p options can be used to attach to up to 32 processes in addition to command (which is optional if at least one -p option is
               given).

它说pid,但iirc在Linux上的pid和tid共享相同的命名空间,这似乎有效:

$ strace -f -p tid1 -p tid2 -p tid3 -p tid4

我认为这可能是你现在能做的最好的事情。但我想有人可以扩展strace用扩展标记的旗帜。在找到流程并附加到流程之间可能仍会存在竞争,其中新流程将被遗漏。它符合关于strace -f的现有警告:

   -f          Trace child processes as they are created by currently traced processes as a result of the fork(2) system call.

               On non-Linux platforms the new process is attached to as soon as its pid is known (through the return value of fork(2) in the  par‐
               ent process). This means that such children may run uncontrolled for a while (especially in the case of a vfork(2)), until the par‐
               ent is scheduled again to complete its (v)fork(2) call.  On Linux the child is traced from its first instruction with no delay.  If
               the  parent  process  decides  to  wait(2)  for  a child that is currently being traced, it is suspended until an appropriate child
               process either terminates or incurs a signal that would cause it to terminate (as determined from the child's current signal dispo‐
               sition).

               On SunOS 4.x the tracing of vforks is accomplished with some dynamic linking trickery.

9
投票

正如在多个评论中所回答的那样,strace -fp <pid>将显示该进程拥有的所有线程的痕迹 - 甚至那些已经在strace开始之前已经生成的进程。

© www.soinside.com 2019 - 2024. All rights reserved.