/* * Scenario 3: The Syscall Storm - Unbuffered I/O * =============================================== * This program reads a file byte-by-byte using raw read() syscalls. * Each byte triggers a context switch to the kernel - extremely slow! * * Compile: gcc -O2 -o read_slow read_slow.c * * EXERCISES: * 1. Create a test file: dd if=/dev/urandom of=testfile bs=1M count=1 * 2. Run: time ./read_slow testfile * 3. Profile: strace -c ./read_slow testfile * 4. Compare with read_fast.c */ #include #include #include #include int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); return 1; } char c; unsigned long byte_count = 0; unsigned long checksum = 0; /* Read one byte at a time - TERRIBLE for performance! */ while (read(fd, &c, 1) == 1) { byte_count++; checksum += (unsigned char)c; } close(fd); printf("Read %lu bytes\n", byte_count); printf("Checksum: %lu\n", checksum); return 0; }