Last active
January 3, 2016 00:39
-
-
Save keeler/8383749 to your computer and use it in GitHub Desktop.
Print threads of a running process. Response to http://stackoverflow.com/questions/21007804/how-do-i-find-threads-that-belong-to-the-same-process-in-linux.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <dirent.h> | |
int main(int argc, char** argv) | |
{ | |
if(argc != 2) | |
{ | |
printf("usage: %s <pid>", argv[0]); | |
return -1; | |
} | |
const int MAX_PID_DIGITS = 30; // Way more than enough. | |
if(strlen(argv[1]) > MAX_PID_DIGITS) | |
{ | |
perror("Are you sure that's a pid...?"); | |
return -1; | |
} | |
char pid[MAX_PID_DIGITS]; | |
strcpy(pid, argv[1]); | |
char filename[MAX_PID_DIGITS + 13]; // As long as it can possibly be with "/proc/<pid>/task\0" | |
sprintf(filename, "/proc/%s/task", pid); | |
struct dirent* entry; | |
DIR* dir = opendir(filename); | |
if(dir == NULL) | |
{ | |
perror("opendir failed"); | |
return -1; | |
} | |
// Iterate over the subdirectories. | |
while((entry = readdir(dir)) != NULL) | |
{ | |
// Ignore '.', '..' directories. | |
// /proc/[pid]/task directory also has a subdirectory | |
// whose name is the pid of /proc/[pid]/task, ignore | |
// that as well. | |
if(strcmp(entry->d_name, ".") == 0 | |
|| strcmp(entry->d_name, "..") == 0 | |
|| strcmp(entry->d_name, pid) == 0) | |
{ | |
continue; | |
} | |
printf("%s\n", entry->d_name); | |
} | |
closedir(dir); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment