Parent directory Makefile fork-then-open.c io.c open-then-fork.c std-io.c
Download
CC=gcc CFLAGS=-g -Wall executables = io std-io open-then-fork fork-then-open objects = io.o std-io.o open-then-fork.o fork-then-open.o .PHONY: default default: $(executables) dd bs=1 count=8192 if=/dev/zero of=bytes.out $(executables): $(objects): .PHONY: clean clean: rm -f *~ *.out $(objects) $(executables) rm -rf *.dSYM .PHONY: all all: clean default
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { char c; int fd; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; const char *pathname = "fork-then-open.out"; if (fork() == 0) sleep(1); fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode); for (c = 'A'; c < 'A' + 5; c++) { write(fd, &c, 1); sleep(2); } close(fd); return 0; }
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define BUF_SIZE 1024 int main(int argc, char **argv) { int fd, n, i = 0; char buf[BUF_SIZE]; // 8KB file fd = open("bytes.out", O_RDONLY); // Read up to 1KB at a time -> loop 8 times while ((n = read(fd, buf, BUF_SIZE)) > 0) { printf("i=%d: got %d bytes\n", i++, n); } close(fd); return 0; }
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { char c; int fd; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; const char *pathname = "open-then-fork.out"; fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode); if (fork() == 0) sleep(1); for (c = 'A'; c < 'A' + 5; c++) { write(fd, &c, 1); sleep(2); } close(fd); return 0; }
#include <stdio.h> #define BUF_SIZE 1024 int main(int argc, char **argv) { FILE *fp; char buf[BUF_SIZE]; int n, i = 0; // 8KB file fp = fopen("bytes.out", "rb"); // Read up to 1KB at a time -> loop 8 times while ((n = fread(buf, 1, BUF_SIZE, fp)) > 0) { printf("i=%d, got %d bytes\n", i++, n); } fclose(fp); return 0; }