pidof.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2018 K. Lange
  5. *
  6. * pidof - Find and print process IDs
  7. *
  8. */
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <stdint.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <unistd.h>
  16. #include <dirent.h>
  17. typedef struct process {
  18. int pid;
  19. int ppid;
  20. int tgid;
  21. char name[100];
  22. char path[200];
  23. } p_t;
  24. #define LINE_LEN 4096
  25. p_t * build_entry(struct dirent * dent) {
  26. char tmp[256];
  27. FILE * f;
  28. char line[LINE_LEN];
  29. sprintf(tmp, "/proc/%s/status", dent->d_name);
  30. f = fopen(tmp, "r");
  31. p_t * proc = malloc(sizeof(p_t));
  32. while (fgets(line, LINE_LEN, f) != NULL) {
  33. char * n = strstr(line,"\n");
  34. if (n) { *n = '\0'; }
  35. char * tab = strstr(line,"\t");
  36. if (tab) {
  37. *tab = '\0';
  38. tab++;
  39. }
  40. if (strstr(line, "Pid:") == line) {
  41. proc->pid = atoi(tab);
  42. } else if (strstr(line, "PPid:") == line) {
  43. proc->ppid = atoi(tab);
  44. } else if (strstr(line, "Tgid:") == line) {
  45. proc->tgid = atoi(tab);
  46. } else if (strstr(line, "Name:") == line) {
  47. strcpy(proc->name, tab);
  48. } else if (strstr(line, "Path:") == line) {
  49. strcpy(proc->path, tab);
  50. }
  51. }
  52. if (strstr(proc->name,"python") == proc->name) {
  53. char * name = proc->path + strlen(proc->path) - 1;
  54. while (1) {
  55. if (*name == '/') {
  56. name++;
  57. break;
  58. }
  59. if (name == proc->name) break;
  60. name--;
  61. }
  62. memcpy(proc->name, name, strlen(name)+1);
  63. }
  64. if (proc->tgid != proc->pid) {
  65. char tmp[100] = {0};
  66. sprintf(tmp, "{%s}", proc->name);
  67. memcpy(proc->name, tmp, strlen(tmp)+1);
  68. }
  69. fclose(f);
  70. return proc;
  71. }
  72. int main (int argc, char * argv[]) {
  73. if (argc < 2) return 1;
  74. int space = 0;
  75. /* Open the directory */
  76. DIR * dirp = opendir("/proc");
  77. int found_something = 0;
  78. struct dirent * ent = readdir(dirp);
  79. while (ent != NULL) {
  80. if (ent->d_name[0] >= '0' && ent->d_name[0] <= '9') {
  81. p_t * proc = build_entry(ent);
  82. if (!strcmp(proc->name, argv[optind])) {
  83. if (space++) printf(" ");
  84. printf("%d", proc->pid);
  85. found_something = 1;
  86. }
  87. }
  88. ent = readdir(dirp);
  89. }
  90. closedir(dirp);
  91. if (!found_something) {
  92. return 1;
  93. }
  94. printf("\n");
  95. return 0;
  96. }