title: How to use PTRACE to get a consistent view of multiple threads?
body: <p>While I was working <a href="https://stackoverflow.com/q/18488598/596781">on this question</a>, I've come across a possible idea that uses <code>ptrace</code>, but I'm unable to get a proper understanding of how <code>ptrace</code> interacts with threads.</p>
  
  <p>Suppose I have a given, multithreaded main process, and I want to attach to a specific thread in it (perhaps from a forked child).</p>
  
  <ol>
  <li><p>Can I attach to a specific thread? (The manuals diverge on this question.)</p></li>
  <li><p>If so, does that mean that single-stepping only steps through that one thread's instructions? Does it stop all the process's threads?</p></li>
  <li><p>If so, do all the other threads remain stopped while I call <code>PTRACE_SYSCALL</code> or <code>PTRACE_SINGLESTEP</code>, or do <em>all</em> threads continue? Is there a way to step forward only in one single thread but guarantee that the other threads remain stopped?</p></li>
  </ol>
  
  <p>Basically, I want to synchronise the original program by forcing all threads to stop, and then only execute a small set of single-threaded instructions by single-stepping the one traced thread.</p>
  
  <p>My personal attempts so far look a bit like this:</p>
  
  <pre><code>pid_t target = syscall(SYS_gettid);   // get the calling thread's ID
  pid_t pid = fork();
  
  if (pid &gt; 0)
  {
      waitpid(pid, NULL, 0);            // synchronise main process
  
      important_instruction();
  }
  else if (pid == 0)
  {
      ptrace(target, PTRACE_ATTACH, NULL, NULL);    // does this work?
  
      // cancel parent's "waitpid" call, e.g. with a signal
  
      // single-step to execute "important_instruction()" above
  
     ptrace(target, PTRACE_DETACH, NULL, NULL);     // parent's threads resume?
  
     _Exit(0);
  }
  </code></pre>
  
  <p>However, I'm not sure, and can't find suitable references, that this is concurrently-correct and that <code>important_instruction()</code> is guaranteed to be executed only when all other threads are stopped. I also understand that there may be race conditions when the parent receives signals from elsewhere, and I heard that I should use <code>PTRACE_SEIZE</code> instead, but that doesn't seem to exist everywhere.</p>
  
  <p>Any clarification or references would be greatly appreciated!</p>