root / logic / trunk / src / kernel_modules / generic / ioctl.c @ 71
History | View | Annotate | Download (1.84 KB)
1 | 71 | Janez1 | /*
|
---|---|---|---|
2 | * ioctl.c − the process to use ioctl's to control the kernel module
|
||
3 | *
|
||
4 | * Until now we could have used cat for input and output. But now
|
||
5 | * we need to do ioctl's, which require writing our own process.
|
||
6 | */
|
||
7 | /*
|
||
8 | * device specifics, such as ioctl numbers and the
|
||
9 | * major device file.
|
||
10 | */
|
||
11 | #include "chardev.h" |
||
12 | #include <stdio.h> |
||
13 | #include <stdlib.h> |
||
14 | #include <fcntl.h> /* open */ |
||
15 | #include <unistd.h> /* exit */ |
||
16 | #include <sys/ioctl.h> /* ioctl */ |
||
17 | /*
|
||
18 | * Functions for the ioctl calls
|
||
19 | */
|
||
20 | ioctl_set_msg(int file_desc, char *message) |
||
21 | { |
||
22 | int ret_val;
|
||
23 | ret_val = ioctl(file_desc, IOCTL_SET_MSG, message); |
||
24 | if (ret_val < 0) { |
||
25 | printf("ioctl_set_msg failed:%d\n", ret_val);
|
||
26 | exit(-1);
|
||
27 | } |
||
28 | } |
||
29 | |||
30 | ioctl_get_msg(int file_desc)
|
||
31 | { |
||
32 | int ret_val;
|
||
33 | char message[100]; |
||
34 | /*
|
||
35 | * Warning − this is dangerous because we don't tell
|
||
36 | * the kernel how far it's allowed to write, so it
|
||
37 | * might overflow the buffer. In a real production
|
||
38 | * program, we would have used two ioctls − one to tell
|
||
39 | * the kernel the buffer length and another to give
|
||
40 | * it the buffer to fill
|
||
41 | */
|
||
42 | ret_val = ioctl(file_desc, IOCTL_GET_MSG, message); |
||
43 | if (ret_val < 0) { |
||
44 | printf("ioctl_get_msg failed:%d\n", ret_val);
|
||
45 | exit(-1);
|
||
46 | } |
||
47 | printf("get_msg message:%s\n", message);
|
||
48 | } |
||
49 | |||
50 | ioctl_get_nth_byte(int file_desc)
|
||
51 | { |
||
52 | int i;
|
||
53 | char c;
|
||
54 | printf("get_nth_byte message:");
|
||
55 | i = 0;
|
||
56 | do {
|
||
57 | c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++); |
||
58 | if (c < 0) { |
||
59 | printf("ioctl_get_nth_byte failed at the %d'th byte:\n",i);
|
||
60 | exit(-1);
|
||
61 | } |
||
62 | putchar(c); |
||
63 | } while (c != 0); |
||
64 | putchar('\n');
|
||
65 | } |
||
66 | |||
67 | /*
|
||
68 | * Main − Call the ioctl functions
|
||
69 | */
|
||
70 | main() |
||
71 | { |
||
72 | int file_desc, ret_val;
|
||
73 | char *msg = "Message passed by ioctl\n"; |
||
74 | file_desc = open(DEVICE_FILE_NAME, 0);
|
||
75 | if (file_desc < 0) { |
||
76 | printf("Can't open device file: %s\n", DEVICE_FILE_NAME);
|
||
77 | exit(-1);
|
||
78 | } |
||
79 | ioctl_set_msg(file_desc, msg); |
||
80 | ioctl_get_nth_byte(file_desc); |
||
81 | ioctl_get_msg(file_desc); |
||
82 | close(file_desc); |
||
83 | } |