puts: Implementing a library function
Easy
xv6 book Sect 1.2 I/O and File descriptors
When you need to print a string without variable interpolation, the puts function from libc is typically used. However, the limited version of libc provided by xv6 does not implement this function. In the previous exercise, you likely used the less efficient printf function. In this exercise, you will implement puts as a library function and modify your solution from the previous exercise to use this new function.
What is puts?
The declaration of puts is as follows:
int puts(const char* str);
The puts function writes the null-terminated string str to stdout, followed by a newline (\n). The return value is >= 0 on success and < 0 on failure.
Task
Implement the puts function in user/puts.c. You should only use the write system call (do not use printf to implement puts). However, you may use other library functions that do not invoke system calls, such as strlen.
A “system call” allows a user program to request a service from the underlying operating system. System calls are standardized in the Portable Operating System Interface (POSIX) standard. While programming user programs, you can look up the expected arguments and return values for a system call using the Linux
mancommand (section 2), for example,man 2 write. Note that, unlike the Linux kernel, xv6 is a small educational operating system that is explicitly not intended to implement the full POSIX standard. Therefore, use the Linux man pages as a guideline, but do not expect xv6 to implement all system calls or edge cases!
The
writesystem call is defined in the xv6 book (Sect 1.2) as “write(fd, buf, n) writes n bytes from buf to the file descriptor fd and returns the number of bytes written. Fewer than n bytes are written only when an error occurs.”
Attention points and hints
- To ensure that all xv6 user-space programs can use
puts, you first need to add its declaration touser/user.h. Then, create a new file (user/puts.c) where you will implementputs. - To ensure this file gets compiled, you must extend the
ULIBvariable in theMakefileto include$U/puts.o. TheULIBvariable contains the object files that are added to all user-space programs, including those that implement library functions. - In UNIX-based operating systems, user programs use “file descriptors” to refer to files when communicating with the operating system. This will be covered in more detail in later lab sessions. For now, it is sufficient to understand that the terminal (
stdout) can also be specified as a special file using a fixed file descriptor number, which is 1. - Always check the return values of system calls and ensure your program handles any errors (e.g.,
writefailure) gracefully. Correctly handling such edge cases will also be important for the coding exam.