xargs: Spawning new processes

Moderate/Hard

xv6 book Sect 1.1 Processes and memory

This exercise will demonstrate the power of combining small UNIX programs with the shell. You will implement a basic version of the xargs UNIX utility.

What is xargs?

xargs is a program that builds and executes command lines from standard input, allowing you to conveniently run a specified command with extended arguments for every input line.

The following examples illustrate the behavior of xargs:

[xv6-shell]$ echo world | xargs echo hello
hello world

In the example, the command executed is echo hello and the additional arguments are the output of the echo world command, resulting in the command echo hello world, which outputs “hello world”.

For multi-line inputs, xargs should process the input line by line, as in the following example:

[xv6-shell]$ cat > names.txt
Alice
Bob
[xv6-shell]$ cat names.txt | xargs echo hello
hello Alice
hello Bob

In the example above, we first create a names.txt file with one name per line (type in “Alice” + <ENTER>, “Bob” + <ENTER>, and finally close the file with CTRL-D). The names.txt file is subsequently read line per line by xargs to be passed to the echo child command.

:information_source: Note that modern implementations of xargs may optimize performance by passing multiple lines to the command simultaneously. However, for this lab, you are not required to implement this optimization. If you wish to run xargs on your GNU/Linux system, make sure to use the -L 1 option to replicate the behavior we aim to implement on xv6.

Task

Create a simple version of xargs for xv6. Your program should:

  1. Accept a command and its arguments from the command line.
  2. Repeatedly read one line at a time from standard input.
  3. For each input line:
    • Create a new process using fork.
    • In the child process, run the specified command using exec, appending the input line as the final argument following the specified command’s arguments
    • In the parent process, wait for the child to finish using wait.

Your implementation should be saved in the file user/xargs.c.

:bulb: Make sure you properly understand the required functionality for xargs and review the step-by-step approach below before starting to hack away at the implementation.

:bulb: Make sure you have carefully read Section 1.1 in the xv6 book to understand how the fork, exec, and wait system calls work.

:bulb: Always check the return values of system calls and ensure your program handles any errors (e.g., fork or exec failure) gracefully. Correctly handling such edge cases will also be important for the coding exam.

Step-by-step guidance

To avoid being overwhelmed, build your solution in small steps:

Step 1: Copy command-line arguments

Familiarize yourself with the argc and argv arguments passed to the main function in C.

The main function of your xargs program will receive the initial command and its arguments via argv[].

  • argv[0] is always the name of the current program (e.g., “xargs”).
  • Do not forget to terminate the argv array with a null pointer and each string with a null byte \0.

Example: invoking xargs echo hello will result in the following argv[] in the main function:

        +-------------+     +---+---+---+---+---+---+
        | argv[0]     | --> | x | a | r | g | s | \0|
        +-------------+     +---+---+---+---+---+---+
        | argv[1]     | --> | e | c | h | o | \0|   |
        +-------------+     +---+---+---+---+---+---+
        | argv[2]     | --> | h | e | l | l | o | \0|
        +-------------+     +---+---+---+---+---+---+
        | argv[3] = 0 |
        +-------------+

Task. As we will need to construct a new extended argument list for the child process, combining the argv passed to main with the lines read from standard input, we first need to copy argv[1..argc-1] into a separate array for later modification. It is okay to allocate a fixed buffer and exit when the provided argc is too large.

Step 2: Read input lines

You can use the following helper function to read one line using the xv6 read system call. You can pass it as fixed-size buffer with a maximum length (e.g., 100 characters). Lines longer than the buffer will be truncated safely.

int readline(int fd, char *buf, int size)
{
    char c;
    int i = 0;

    while ((i < size - 1) && read(fd, &c, 1) > 0)
    {
        if (c == '\n')
        {
            buf[i] = '\0';
            return i + 1;
        }
        else
            buf[i] = c;
        i++;
    }

    /* Truncate the line if it exceeds the buffer size */
    buf[i] = '\0';

    /* Consume and discard the rest of the line */
    while (read(fd, &c, 1) > 0 && c != '\n');

    return i;
}

Task. Call readline() in a loop to process stdin one line at a time.

Step 3: Fork, exec, wait

For each input line:

  1. Call fork() to create a child process.
  2. In the child:
    • Prepare the extended args array (see Step 4).
    • Call exec() to run the command.
  3. In the parent:
    • Call wait() to wait for the child to finish before processing the next line.

You can initially test the child process with only the original argv[1..argc-1], and add the input line later. Make sure the child’s argument list ends with a null byte for exec to work.

Step 4: Constructing the extended argument array

Finally create the extended argument list for the child process that should look as follows (given the original argc passed to xargs):

args[0..argc-2] = command and arguments passed to xargs
args[argc-1] = input line
args[argc] = 0

Note that:

  • The first element of args should always be the name of the child process.
  • Each string in args must be null-terminated (\0).
  • The args array itself must be terminated with a null pointer (0).
  • You may pass the input line as a single string, which may include spaces.

This site uses Just the Docs, a documentation theme for Jekyll.