shithub: plan9front

ref: e72da62915b09d5673b0c0179ba8dfe045aeb8c3
dir: /sys/man/9/parsecmd/

View raw version
parsecmd, cmderror, lookupcmd
\- parse device commands
.ta \w'\fLCmdbuf* 'u
Cmdbuf*	parsecmd(char *a, int n)
void		cmderror(Cmdbuf *cb, char *s)
Cmdtab*		lookupcmd(Cmdbuf *cb, Cmdtab *ctab, int nctab)
.I Parsecmd
is an interface to
.I tokenize
.IR getfields (2)),
that safely parses a command, with blank-separated fields, as might be
written to a device's
.B ctl
The buffer
.I a
and count
.I n
can be those passed to the driver's
.I write
.I Parsecmd
converts the byte array (which might not be null-terminated) to a null-terminated string,
trimming any trailing new line,
before invoking
.I tokenize
to break the string into arguments, interpreting blank and tab as field separators
when they are not quoted
(in the style of
.IR rc (1)).
It returns a pointer to a dynamically-allocated
.B Cmdbuf
which holds a copy of the string and the resulting fields; it is
defined as follows:
.ta 6n +\w'char* 'u
struct Cmdbuf
	char	*buf;
	char	**f;
	int	nf;
} Cmdbuf;
The array
.B f
holds the field pointers;
.B nf
gives the number of fields.
.B Cmdbuf
is allocated by
.I smalloc
.IR malloc (9)),
and the caller is responsible for freeing it using
.IR free .
.I Cmderror
prepends the given format with the original command,
then calls
.IR error (9).
Command strings may be turned into a (typically enumerated)
integer with 
.IR lookupcmd .
The catchall
.L *
matches any text.  Unrecognized commands, or commands
given an unacceptable number of arguments generate a
call to
.IR error .
The definition is as follows
.ta 6n +\w'char* 'u
struct Cmdtab
	int	index;  /* used by client to switch on result */
	char	*cmd;   /* command name */
	int	narg;   /* expected #args; 0 ==> variadic */
} Cmdtab;
The integer
.B index
is the number returned on command match.
The string
.B cmd
is the command name, and
.B narg
is 0 (indicating a variadic function) or the
number of arguments.
.B /sys/src/9/port/parse.c