Advertisement
Guest User

getppidbypid

a guest
Nov 30th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3.  
  4. int getppidbypid(int pid)
  5. {
  6.     int p, pp;
  7.     FILE *F;
  8.     char buf[256];
  9.  
  10.     sprintf(buf, "ps -o pid,ppid -p %d", pid);
  11.  
  12.     F = popen(buf, "r");
  13.     if (!F) {
  14.         /* Can not run ps */
  15.         return -1;
  16.     }
  17.  
  18.     while (!feof(F)) {
  19.         if (!fgets(buf, sizeof(buf), F)) {
  20.             pclose(F);
  21.             return -1;
  22.         }
  23.  
  24.         if (sscanf(buf, "%d %d", &p, &pp) > 0) {
  25.             if (p == pid) {
  26.                 pclose(F);
  27.                 return pp;
  28.             }
  29.         }
  30.     }
  31.  
  32.     pclose(F);
  33.  
  34.     return -1; /* Not found */
  35. }
  36.  
  37. int main(int argc, char *argv[])
  38. {
  39.     int i;
  40.     int p;
  41.  
  42.     for (i = 1; i < argc; i++) {
  43.         p = atoi(argv[i]);
  44.  
  45.         printf("[%d] -> [%d]\n", getppidbypid(p), p);
  46.     }
  47.  
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement