1)定義
1 2 3 |
#include <linux/proc_fs.h> /* Needed by proc entry */ int aegis_enable = 1; |
2)宣告
1 |
static struct proc_dir_entry *entry_aegis_enable = NULL; |
3)Kernel主體
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
/* read operation for /proc/net/aegis/aegis_enable entry */ ssize_t proc_aegis_enable_read(struct file *file, char *ubuf, size_t bytes, loff_t *pos) { char buf[16]; int len=0, rlen; if(bytes < 0) return -EINVAL; if(bytes == 0) return 0; /*print message here*/ len += snprintf(buf + len, 16, "%d", aegis_enable); if (*pos >= len) return 0; rlen = len - *pos; if (rlen > bytes) rlen = bytes; if (copy_to_user(ubuf, buf + *pos, rlen)) return -EFAULT; *pos += rlen; return rlen; } /* write operation for /proc/net/aegis/aegis_enable entry */ ssize_t proc_aegis_enable_write(struct file *file, const char *buf, size_t bytes, loff_t *pos) { unsigned char tmp[16]; int tmpval = 0, retval = 0, i = 0; memset(tmp, 0, 16); if (bytes > 0) { if (*pos == 0) tmp[0]=0x00; retval = copy_from_user(tmp + *pos, buf, bytes); if (retval != 0) { printk("proc_aegis_enable_write: copy_from_user() failed!\n"); return -EFAULT; } *pos += bytes; tmp[*pos] = '\0'; for (i = 0; tmp[i] != 0; i++) { if (tmp[i] >= '0' && tmp[i] <= '9') tmpval = (tmpval * 10) + (tmp[i] - '0'); else /* Some other crap */ break; } aegis_enable = tmpval; } return bytes; } static struct file_operations aegis_enable_file_ops = { read: proc_aegis_enable_read, write: proc_aegis_enable_write, }; |
4)在module_init的function裡
1 2 3 4 5 6 |
/* create /proc/net/aegis/aegis_enable entry*/ entry_aegis_enable = create_proc_entry ("aegis_enable", 0644, dir_aegis); if (entry_aegis_enable) { entry_aegis_enable->proc_fops = &aegis_enable_file_ops; entry_aegis_enable->owner = THIS_MODULE; } |
5)在module_exit的function裡
1 |
remove_proc_entry("aegis_enable", dir_aegis); |
6) 在userspace把PROC讀取出來
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#define PROC_AEGIS_ENABLE_PATH "/proc/net/aegis/aegis_enable" int get_DOS_status(void) { FILE *fp; int i, c, dosEnable = 0; char buf[32]; /* DOS_status check */ fp = fopen(PROC_AEGIS_ENABLE_PATH, "r"); if(fp != NULL){ c = fgetc(fp); snprintf(buf, sizeof(buf), "%c", (char)c); if(i < 32 && !feof(fp)){ fprintf(stderr, "DOS_Status error reading.\n"); } fclose(fp); } else { fprintf(stderr, "%s error opening.\n", PROC_AEGIS_ENABLE_PATH); fclose(fp); return -1; } dosEnable = atoi(buf); return dosEnable; } |