This is the 22nd day of my participation in the August More Text Challenge

Xv6 pipeline

Reference: Xv6-RISCV-Book 1.3 Pipes

pipe

The Xv6 system calls pipe() to create the pipe. Pipes are similar to chan in the Go language. We use | said the pipeline in the Shell, to command: echo “hello world” | wc, can use the following code:

// upipe.c

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(a) {
	int p[2];  // file descriptors for the pipe
	
	char *argv[2];
	argv[0] = "wc";
	argv[1] = 0;  // NULL

	pipe(p);  // creates a new pipe: records the read and write file descriptors in the array p

	if (fork() == 0) {
		// redirection
		close(0);
		dup(p[0]);  // stdin = <- pipe

		close(p[0]);
		close(p[1]);

		exec("wc", argv);
	} else {
		close(p[0]);

		write(p[1]."hello world\n".12);  // pipe <- str

		close(p[1]);
	}

	exit(0);
}
Copy the code

Compile and run:

$ upipe
1 2 12
Copy the code

The implementation of pipe handling in Xv6 SH is similar to this code: fork two processes to redirect the standard output or input and run commands on the left and right sides of the pipe. See the user/sh. C: 100.

Pipeline V.S. temporary file

There seems to be little difference between using pipes and temporary files:

# pipeline
echo "hello world" | wc
Copy the code
# temporary file
echo hello world >/tmp/xyz; wc </tmp/xyz
Copy the code

But pipes are better:

  • Pipes are cleaned automatically (temporary files should be manually deleted)
  • Pipes can hold streams of any length (sufficient disk space is required for temporary files)
  • Pipes can be run in parallel (temporary files can only be run in one, and then started in the second)
  • Blocking reads and writes on pipes are more convenient than non-blocking temporary files when dealing with interprocess communication problems.

EOF


By CDFMLR 2021-02-20

Echo “See you 🪐”

The picture at the top is from xiaowei API, which is randomly selected and only used to test the mechanical and photoelectric performance of the screen. It has nothing to do with any content or opinion of the article, and does not mean that I agree with, support or oppose any content or opinion in part or in whole. If there is infringement, contact delete.