fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // This function counts the number of digit places in 'pid'
  6. int pid_digit_places(int pid)
  7. {
  8. int n = pid;
  9. int places = 0;
  10. while (n)
  11. n /= 10;
  12. places++;
  13. return places;
  14. }
  15.  
  16. char *construct_path(int pid, char *dir)
  17. {
  18. // get count of places in pid
  19. int places = pid_digit_places(pid);
  20. char *pid_str = calloc(places, sizeof(char));
  21.  
  22. // create string of pid
  23. sprintf(pid_str, "%d", pid);
  24.  
  25. char *proc = "/proc/";
  26. size_t plen = strlen(proc);
  27. size_t dlen = strlen(dir) + 1;
  28. char *path = calloc(plen + dlen + places, sizeof(char));
  29.  
  30. strcat(path, proc);
  31. strcat(path, pid_str);
  32. strcat(path, dir);
  33.  
  34. return path;
  35. }
  36.  
  37. void fd_walk(int pid)
  38. {
  39. char *fd = "/fd/";
  40. char *fdpath = construct_path(pid, fd);
  41.  
  42. // prints "/proc/573/fd/ - as expected
  43. printf("Before: %s\n", fdpath);
  44.  
  45. // shows a length of 13
  46. printf("Size Before: %d\n", (int)strlen(fdpath));
  47.  
  48.  
  49. char *test = calloc(strlen(fdpath) + 1, sizeof(char));
  50. strcpy(test, fdpath);
  51.  
  52. // prints "/proc/573/fd" no trailing "/"
  53. printf("Copied Str: %s\n", test);
  54.  
  55. //shows a length of 13 though
  56. printf("Copied Size: %d\n", (int)strlen(test));
  57.  
  58. // prints "/proc/573/fd" no trailing "/" now
  59. printf("After: %s\n", fdpath);
  60.  
  61. // still shows length of 13
  62. printf("Size After: %d\n", (int)strlen(fdpath));
  63. }
  64.  
  65. int main(void)
  66. {
  67. // integer to create path around
  68. int pid = 573;
  69. fd_walk(pid);
  70. return 0;
  71. }
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
Before: /proc/573/fd/
Size Before: 13
Copied Str: /proc/573/fd
Copied Size: 13
After: /proc/573/fd
Size After: 13