When I'm parsing process IDs from /proc, obviously each thread of a process gets its own ID. And I realize that all the threads in that same process can be gathered from /proc/${pid}/task/.

But my question is, can I assume that the first ID in the list (the lowest numbered one?) is the main thread of the process?

The goal I'm ultimately trying to do is write a quick ps script in python without using a subprocess or invoking the shell.


You can't assume that, process ids (and thread ids) can be reused, so the ordering is not guaranteed. (That's not likely on a freshly booted 64bit system, but you'll see it on machines with large uptimes.)

You can get the thread group id (which is the process id) from the /proc/${id}/status. It's in the line Tgid: nnnnn.


$ cat /proc/8288/status 
Name:   vlc
State:  S (sleeping)
Tgid:   8281               // main vlc process id
Pid:    8288               // thread id
  • That's a good point about reuse of pids. Don't know why I didn't think of that. This IS on an embedded, long running system. But new processes should very rarely be spawned anyway. However /proc/${pid}/task will include the thread pid. So if /proc/1/task has entries "1, 3, 5". /proc/3/task/ will also contain "1, 3, 5". So you can't assume that ${pid} is the main process ID. – Falmarri Jun 22 '11 at 18:18
  • you're right, I didn't think it did that but it does. Updated with another possibility. – Mat Jun 22 '11 at 18:31
  • That's probably the best I'll be able to get. It's not all that important anyway. So good enough =] – Falmarri Jun 28 '11 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.