27.21Extending the I/O subsystem. 4tH 4tH Forth compiler
Quảng cáo
Quảng cáo
CHAPTER 27. MODIFYING 4TH 543
27.21
Extending the I/O subsystem
The 4tH I/O system is entirely built upon the buffered C streams
6 concept. That means every device that can be assigned to a FILE* and accessed through fgetc() and fputc() can be integrated into the 4tH I/O system. If can open a device with fopen() and close it with fclose(), you’re done, it’s already supported. If not, you have to design two functions that take the same parameters and return the same values as fopen() and fclose()
. If you can’t you can probably still use those devices within 4tH, but you can’t integrate them into the I/O system.
If you have defined these functions, you’ll have to make changes to OpenStream() in exec_4th() . ’Mode’ is the sum of all file access methods, e.g.
s" ls" input pipe + open
This definition contains two file access methods, INPUT and PIPE. You can find these values in cmds_4th.h. INPUT equals 1 and PIPE equals 8. That makes 9 and that is what ends up in the ’Mode’ parameter of OpenStream(). However, if one would allow all possible combinations of all file access methods some would surely make little sense. That is why ’Mode’ is filtered by Mapping[]. You will find that element 9 of Mapping[]
7 contains the value 5. That number corresponds to element 5 in Modelist[], which lists the correct file access method (which is still 9, of course) and the mode parameter for fopen()
. OpenStream() continues by initializing the members of the Stream[] structure.
M
EMBER
F
UNCTION
Mode
Device
Connect
Uniform file access method
FILE pointer to opened device
Function pointer to fopen() like function
Disconnect
Function pointer to fclose() like function
Table 27.11: Members of Stream[] structure
When this is done, it uses the Connect() member to open the device. After that, everything is completely transparent to the programmer.
If you want to add a new device, you probably want to signal which type of device you’re using. In order to do that, you must first add a #define to the ’file modes’ section in cmds_4th.h. Each new file access method has exactly twice the value of the previous one, which means that the first one you define would have to be 16. Then you have to figure out which modes are actually supported. Can your device be opened in read-write mode?
Does appending make sense? You add those ’ideal’ states to ModeList[]. Then map all possible combinations of all file access methods to the ’ideal’ states in ModeList[] using Mapping[] conversion table. Every additional file access method doubles the size of Mapping[], so beware!
M
ACRO
F
UNCTION
THROW
DEV(n) Aborts if n is not a device M4BADDEV
UDEV(n)
Aborts if n is not opened by the user
M4BADDEV
ODEV(n) Aborts if n is not opened
SDEV(n)
Aborts if n is a pipe
M4IOERR
M4BADDEV
Table 27.12: Device status macros
6
See: http://www.aquaphoenix.com/ref/gnu_c_library/libc_118.html
7
We start counting at 0.
Tải xuống
Quảng cáo