fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdint.h>
  4. #include <fcntl.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7.  
  8. unsigned long virt_to_phys(void *virt_addr) {
  9. int fd = open("/proc/self/pagemap", O_RDONLY);
  10. if (fd < 0) {
  11. perror("open");
  12. return 0;
  13. }
  14.  
  15. unsigned long virt_pfn;
  16. unsigned long offset = ((unsigned long)virt_addr / getpagesize()) * sizeof(unsigned long);
  17. if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
  18. perror("lseek");
  19. close(fd);
  20. return 0;
  21. }
  22.  
  23. if (read(fd, &virt_pfn, sizeof(virt_pfn)) != sizeof(virt_pfn)) {
  24. perror("read");
  25. close(fd);
  26. return 0;
  27. }
  28.  
  29. close(fd);
  30.  
  31. if (!(virt_pfn & (1ULL << 63))) {
  32. return 0; // page not present
  33. }
  34.  
  35. unsigned long phys_pfn = virt_pfn & ((1ULL << 55) - 1);
  36. return (phys_pfn * getpagesize()) + ((unsigned long)virt_addr % getpagesize());
  37. }
  38.  
  39. int main() {
  40. int a = 5;
  41. if (fork() == 0) {
  42. a = a + 5;
  43. printf("Child: value=%d, virt=%p, phys=%lx\n", a, &a, virt_to_phys(&a));
  44. } else {
  45. a = a - 5;
  46. printf("Parent: value=%d, virt=%p, phys=%lx\n", a, &a, virt_to_phys(&a));
  47. }
  48. return 0;
  49. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Parent: value=0, virt=0x7ffcb07e5e44, phys=e44
Child: value=10, virt=0x7ffcb07e5e44, phys=e44