Writing a basic 9P server
On plan 9 the entire system is build around the idea of namespaces and that "everything is a file". For this reason it is very easy to write a new 9P fileserver in C since all the boring tasks are implemented in libraries. This note describes a minimal program which serves a folder to /mnt/hello9p
containing a single synthetic file with the contents "Hello from 9P!".
The code
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
void
fsread(Req *r)
{
readstr(r, "Hello from 9P!\n");
respond(r, nil);
}
Srv fs = {
.read = fsread,
};
void
main(void)
{
Tree *tree;
tree = alloctree(nil, nil, DMDIR|0555, nil);
fs.tree = tree;
createfile(tree->root, "hello", nil, 0555, nil);
postmountsrv(&fs, nil, "/mnt/hello9p", MREPL | MCREATE);
}
Explanation
The global variable fs
is a structure which contains function pointers to all the 9P handlers, but since I only plan on reading from the file, only the read
field is set. The fsread function calls two helper functions from the 9p(2) library which will create a response with the given string as the file contents.
In main
I start by allocating a new file tree, since this 9P server deals with a fileserver that has a tree structure, and therefore I don't have to worry about how directories are handled for example. A file is added with createfile
to the root of the tree.
The call to postmountsrv
will mount the 9P server under /mnt/hello9p
.
Thats it
This is not very complicated, but see the manpages at 9p(2) and 9pfile(2) and intro(5) for more information about the libraries and 9P itself.