All of the examples in this section use two functions, copyData() and die().copyData() reads data from a file descriptor and writes it to another as long as data is left to be read. die() calls perror() and exits the program. We put both of these functions in the file sockutil.c to keep the example programs a bit cleaner. For reference, here is the implementation of these two functions:
1: /* sockutil.c */ 2: 3: #include <stdio.h> 4: #include <stdlib.h> 5: #include <unistd.h> 6: 7: #include "sockutil.h" 8: 9: /* issue an error message via perror() and terminate the program */ 10: void die(char * message) { 11: perror(message); 12: exit(1); 13: } 14: 15: /* Copies data from file descriptor 'from' to file descriptor 16: 'to' until nothing is left to be copied. Exits if an error 17: occurs. This assumes both from and to are set for blocking 18: reads and writes. */ 19: void copyData(int from, int to) { 20: char buf[1024]; 21: int amount; 22: 23: while ((amount = read(from, buf, sizeof(buf))) > 0) { 24: if (write(to, buf, amount) != amount) { 25: die("write"); 26: return; 27: } 28: } 29: if (amount < 0) 30: die("read"); 31: }