thread_map.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <dirent.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include "thread_map.h"
  5. /* Skip "." and ".." directories */
  6. static int filter(const struct dirent *dir)
  7. {
  8. if (dir->d_name[0] == '.')
  9. return 0;
  10. else
  11. return 1;
  12. }
  13. struct thread_map *thread_map__new_by_pid(pid_t pid)
  14. {
  15. struct thread_map *threads;
  16. char name[256];
  17. int items;
  18. struct dirent **namelist = NULL;
  19. int i;
  20. sprintf(name, "/proc/%d/task", pid);
  21. items = scandir(name, &namelist, filter, NULL);
  22. if (items <= 0)
  23. return NULL;
  24. threads = malloc(sizeof(*threads) + sizeof(pid_t) * items);
  25. if (threads != NULL) {
  26. for (i = 0; i < items; i++)
  27. threads->map[i] = atoi(namelist[i]->d_name);
  28. threads->nr = items;
  29. }
  30. for (i=0; i<items; i++)
  31. free(namelist[i]);
  32. free(namelist);
  33. return threads;
  34. }
  35. struct thread_map *thread_map__new_by_tid(pid_t tid)
  36. {
  37. struct thread_map *threads = malloc(sizeof(*threads) + sizeof(pid_t));
  38. if (threads != NULL) {
  39. threads->map[0] = tid;
  40. threads->nr = 1;
  41. }
  42. return threads;
  43. }
  44. struct thread_map *thread_map__new(pid_t pid, pid_t tid)
  45. {
  46. if (pid != -1)
  47. return thread_map__new_by_pid(pid);
  48. return thread_map__new_by_tid(tid);
  49. }
  50. void thread_map__delete(struct thread_map *threads)
  51. {
  52. free(threads);
  53. }