1 #include <sys/types.h> 2 #define _KERNEL_STRUCTURES 3 #include <sys/file.h> 4 #include <sys/kinfo.h> 5 6 #include <err.h> 7 #include <fcntl.h> 8 #include <kvm.h> 9 #include <limits.h> 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <unistd.h> 13 14 static void 15 usage(const char *cmd) 16 { 17 fprintf(stderr, "%s [-N kern] [-M core]\n", cmd); 18 exit(1); 19 } 20 21 static const char * 22 typestr(short type) 23 { 24 static char buf[32]; 25 26 switch (type) { 27 case DTYPE_VNODE: 28 return "file"; 29 case DTYPE_SOCKET: 30 return "socket"; 31 case DTYPE_PIPE: 32 return "pipe"; 33 case DTYPE_FIFO: 34 return "fifo"; 35 case DTYPE_KQUEUE: 36 return "kqueue"; 37 case DTYPE_CRYPTO: 38 return "crypto"; 39 case DTYPE_MQUEUE: 40 return "mqueue"; 41 default: 42 snprintf(buf, sizeof(buf), "?%d", type); 43 return buf; 44 } 45 } 46 47 int 48 main(int argc, char *argv[]) 49 { 50 const char *file, *core; 51 char *errbuf; 52 kvm_t *kd; 53 int opt, kfile_cnt, i; 54 struct kinfo_file *kfile; 55 56 file = NULL; 57 core = NULL; 58 59 while ((opt = getopt(argc, argv, "M:N:")) != -1) { 60 switch (opt) { 61 case 'M': 62 core = optarg; 63 break; 64 65 case 'N': 66 file = optarg; 67 break; 68 69 default: 70 usage(argv[0]); 71 } 72 } 73 74 errbuf = malloc(_POSIX2_LINE_MAX); 75 if (errbuf == NULL) 76 err(2, "malloc %d failed", _POSIX2_LINE_MAX); 77 78 kd = kvm_openfiles(file, core, NULL, O_RDONLY, errbuf); 79 if (kd == NULL) 80 errx(2, "%s", errbuf); 81 82 kfile = kvm_getfiles(kd, 0, 0, &kfile_cnt); 83 if (kfile == NULL) 84 errx(2, "kvm_getfiles failed %s", kvm_geterr(kd)); 85 86 for (i = 0; i < kfile_cnt; ++i) { 87 printf("pid %d, fd %d, type %s\n", 88 kfile[i].f_pid, kfile[i].f_fd, typestr(kfile[i].f_type)); 89 } 90 91 kvm_close(kd); 92 93 return 0; 94 } 95