OSDN Git Service

2002-03-01 David O'Brien <obrien@FreeBSD.org>
[pf3gnuchains/pf3gnuchains3x.git] / winsup / cygwin / how-fhandlers-work.txt
1 Copyright 2001 Red Hat Inc., Robert Collins
2
3 fhandlers are the core mechanism by which cygwin provides a file descripter (fd)
4 interface to things such as a random number generated, winsock sockets, raw disk
5 devices, the clipboard, the console and so on. Under unix access to all such
6 devices is via a combination of IOCTL's and open/close/read/write calls. Some
7 special functions do exist - such as bind () and listen () for sockets, but
8 these consistently operate on fd's. Under Win32 there are disparate interfaces
9 that have little in common with each other. See for example Direct Sound and
10 the Clipboard.
11
12 The fhandler class provides all open,read,write,close, ioctl and fork()/exec()
13 functionality for the fd interface. The base class operates on win32 backed
14 files. The various derived classes utilise win32 primitives to provide their
15 specific functionality.
16
17 When a file is opened - not necesarily via open() a fd is assigned to it. The fd
18 includes a pointer to the actual fhandler that operates this specific file. All
19 file-oriented system calls then operate off this basic structure.
20
21 For example, lets examine lseek ().
22
23 extern "C" off_t
24 _lseek (int fd, off_t pos, int dir)
25 {
26   off_t res;
27   sigframe thisframe (mainthread);
28
29   if (dir != SEEK_SET && dir != SEEK_CUR && dir != SEEK_END)
30     {
31       set_errno (EINVAL);
32       res = -1;
33     }
34   else if (cygheap->fdtab.not_open (fd))
35     {
36       set_errno (EBADF);
37       res = -1;
38     }
39   else
40     {
41       res = cygheap->fdtab[fd]->lseek (pos, dir);
42     }
43   syscall_printf ("%d = lseek (%d, %d, %d)", res, fd, pos, dir);
44
45   return res;
46 }
47
48 The sigframe thisframe (mainthread); is signal related - see
49 "how_signals_work.txt".
50
51 The if, else if, else tests (in order)
52 * the validity of the dir parameter,
53 * is the fd being passed actually open? (cannot seek on a closed fd)
54 * call the lseek virtual function in the associated fhandler.
55
56 So as you can see, there is no code that attempts to understand the nature of
57 the fhandler.
58
59 fhandlers that make cross-function-call use of win32 objects that are not
60 inheritable cross-process need to implement fixup-after-fork and recreate those
61 objects. HANDLES can be inherited, but memory mapped regions (for example)
62 cannot.
63
64 For an example step-by-step to create a new fhandler, see
65 ../doc/fhandler-tut.txt