CS360 Midterm Exam: March 2, 2004. Question 1
|
Behold the following system call:
int send_to_card(char *ptr, int nbytes);
This sends the bytes specified by ptr and nbytes
to a special card on your computer. Nbytes must be
less than 4096. It returns 0 on success, and -1 on
failure.
Your job is to write:
int bsend_to_card(char *ptr, int nbytes);
bsend_to_card() gives you two features:
- It performs buffering, so that calls where nybtes is
small will typically not be penalized with system call overhead.
- It allows nbytes to be greater than 4096 bytes.
bsend_to_card() will work as follows. It will manage a
4096-byte buffer in the following way:
- If bsend_to_card() is called, and the
specified memory will fit in the buffer, it copies the specified
memory to the buffer and returns.
- If bsend_to_card() is called when the buffer is
not empty, and the and specified memory will not fit into the buffer,
then the buffer is flushed by calling send_to_card()
on the bytes in the buffer, and the process is repeated with
an empty buffer.
- If bsend_to_card() is called when the buffer is empty,
and the specified memory will not fit into the buffer, then
send_to_card() is called with the first 4096 bytes of
the specified memory, and the process is repeated with the remaining
bytes of the specified memory.
- If bsend_to_card() is called with nbytes equal
to zero, then the buffer is flushed.
As an example, suppose the buffer holds 1000 bytes, and
bsend_to_card(0x10000, 8192) is called. bsend_to_card()
will do the following things:
- Since the specified memory will not fit into the buffer, and the
buffer is not empty, the buffer will be flushed by a call to
send_to_card(buffer, 1000).
- Since the specified memory will not fit into an empty buffer,
send_to_card(0x10000, 4096) is called.
- The remaining 4096 bytes will fit into the empty buffer, so they
are copied there, and bsend_to_card() returns zero.
If send_to_card() ever returns -1, bsend_to_card() should
instantly return -1. Otherwise, bsend_to_card() should return
0 when it is done.
You will need global variables for this. I am including an
answer sheet for this problem that includes the proper declarations
for global variables. You may add more if you want, but you do not
have to.