CS 3733 Operating Systems Notes: Programming In Unix



Command line arguments:

Figure 1.1 (page 18): The argv array for the call mine -c 10 2.0.


Sometimes it is necessary to create a structure like this yourself from a string.
The shell must do this when you execute a command.

argv[] is an array of pointers to chars
In C, this is the same as a pointer to a pointer to a char.

One way to write a function to do this is:
char **makeargv(char *s)
Example 1.9 shows how to use this function.

If you want to return the number of tokens, you can pass a pointer to the arg array as in:
int makeargv(char *s, char ***argvp)
Example 1.11 show how to use this one.

The version we will use has an additional parameter that specifies a string of delimiters:
int makeargv(const char *s, const char *delimiters, char ***argvp)
The const for the first two parameters indicates that the strings should not be modified by the function.

Program 1.1 shows a use of this version.


How to write makeargv

Can use strtok:

#include <string.h>
char *strtok(char *s1, const char *s2);

s1 is the string to parse
s2 is a string of delimiters
returns a pointer to the next token to NULL if none left.
First call: s1 points to the string to parse
Additional calls: s1 is NULL.
Note: the string s1 is modified.

We do not want the string passed to makeargv to be modified so we allocate space for another copy of the string.


Figure 1.2 (page 21): The makeargv makes a working copy of the string s so that it does not modify that input paramter.


Figure 1.3 (page 22): The use of strtok to allocate strings in place for makeargv.

Program 1.2 shows an implementation of makeargv.


Making Functions Safe

strtok is not safe to use with threads since it remembers the previous state.

Another version is available: strtok_r in which you pass another parameter which is used to remember where it is.

#include <string.h>
char *strtok_r(char *s1, const char *s2, char **lasts);

You must declare a char pointer to hold the current position and pass a pointer to it as the last argument to strtok_r.


Programs that use strtok can fail even if they do not involve signals or multiple threads.

Suppose you are given the task to write a program that caclualtes the average number of words per line in a text file. You write a function:
double wordaverage(char *s);
to do this.
You parse the intput string into lines using strtok and call a function
int wordcount(char *s);
to count the words in each line. You assign the task of implemnting wordcount to another programmer.

If the other programmer also uses strtok in the implementation of wordcount, your program will fail.

Each of wordcount and wordaverage is correct by itself, but they do not work together correctly.

You can solve this problem by using strtok_r in either function.