ECEC 201 · Week 7

Modern Computer: Von Neumann

Linux shows the system as files.

Week 7 of 10 · Das Frite

ECEC 201 · Week 7 · In class

Linux shows the system as files.

ECEC 201 · Week 7 · In class

The board's model and its uptime are files under /proc.

ECEC 201 · Week 7 · Lecture

Four calls move every byte

CallReturnsOn failure
open(path, flags)a small non-negative int-1, sets errno
read(fd, buf, n)bytes read; 0 at end of file-1, sets errno
write(fd, buf, n)bytes written-1, sets errno
close(fd)0-1, sets errno

These are system calls, not the stdio library: no buffering, no FILE *.

ECEC 201 · Week 7 · Lecture

Reading a /proc file

#include <fcntl.h>
#include <unistd.h>
/* Reads path into buf as a string; returns length or -1. */
ssize_t read_text(const char *path, char *buf, size_t size)
{
	int fd = open(path, O_RDONLY);
	if (fd < 0)
		return -1;
	ssize_t n = read(fd, buf, size - 1);
	close(fd);
	if (n >= 0)
		buf[n] = '\0';
	return n;
}

ECEC 201 · Week 7 · Lecture

When a call fails: errno

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
	int fd = open("/no/such/file", O_RDONLY);
	if (fd < 0)
		printf("open: %s\n", strerror(errno));
	return 0;
}

ECEC 201 · Week 7 · Lecture

Appending to a log

ECEC 201 · Week 7 · Lab

Lab

  1. In C, with `open` and `read`, print the board model from `/proc/device-tree/model` and the uptime from `/proc/uptime`.
  2. With `write`, append the uptime to a log file, and open a path that does not exist to print its `errno` message. Second pass: run the program five times and keep the five log lines.

ECEC 201 · Week 7 · Lab

Lab (continued)

  1. Assemble the lab hand-in: The program, the board model it printed, the five log lines, and the error line for the missing path.

ECEC 201 · Week 7 · Lab

Hand in

The program, the board model it printed, the five log lines, and the error line for the missing path.

ECEC 201 · Week 7 · Homework

Homework

ECEC 201 · Week 7 · Homework

Turn in

The definition and the three descriptors.

ECEC 201 · Week 7 · Read

Read

On the lab site: Module 10, I/O, reaches devices through drivers. This week grades a C program that reads the system through files.

ECEC 201 · Week 7 · Next

Week 8

A register is a byte whose bits mean different things.

Arrow keys or space to move, F for full screen, N for speaker notes, Home and End for the first and last slide. Print gives one slide per page.