Codes

1. Max One Argument (-n 1)

Instead of appending the whole line as one string, this variation splits the line by spaces and executes the command separately for every single word found.

// Inside main()
int max_per_exec = 1; // Default changed from 0 to 1
int arg_start = 1;

// If user provides -n, it will overwrite this default
if (argc >= 4 && strcmp(argv[1], "-n") == 0) {
    max_per_exec = atoi(argv[2]);
    arg_start = 3;
}

2. Custom Input Delimiter

Changes the character used to signal the end of an argument set. In this case, we use a semicolon.

static int
readline(int fd, char *buf, int max)
{
  int n = 0;
  char c;
  while (n < max - 1) {
    if (read(fd, &c, 1) < 1) break;
    if (c == ';') break; // Changed delimiter to semicolon
    buf[n++] = c;
  }
  buf[n] = '\0';
  return n;
}

3. Verbose Mode

Prints the command and all its arguments to the console so you can see exactly what xargs is about to do.

4. Ignore Empty Lines

Checks the length of the string buffer after reading. If it's just a newline or empty, the iteration is skipped.

5. Prepend Input Argument

Rearranges the argument array so that the input line from stdin becomes the very first argument after the command name.

6. Exit on Error

Inspects the exit status of the child process. If the child failed (status != 0), the parent xargs process terminates immediately.

7. File Input Support

Instead of reading from file descriptor 0 (stdin), it opens a file provided as a second command-line argument and reads from it.

8. Dry-Run Mode

A safety feature that logs the intended action to the screen but skips the actual fork and exec calls.

9. Synchronous Wait

Moves the wait(0) call outside of the reading loop. This allows xargs to spawn all child processes quickly (parallel execution) and only finish once the last one is done.

10. Arg Limit Per Line (Max 3)

If a single input line contains 5 words, this version will run the command once with the first 3 words, and again with the remaining 2.

Last updated