1: /* 2: * Program: sleep.c 3: * Copyright: 1997, sms 4: * Author: Steven M. Schultz 5: * 6: * Version Date Modification 7: * 1.0 1997/9/25 1. Initial release. 8: */ 9: 10: #include <stdio.h> /* For NULL */ 11: #include <sys/types.h> 12: #include <sys/time.h> 13: 14: /* 15: * This implements the sleep(3) function using only 3 system calls instead of 16: * the 9 that the old implementation required. Also this version avoids using 17: * signals (with the attendant system overhead) and returns the amount of 18: * time left unslept if an interrupt occurs. 19: * 20: * The error status of gettimeofday is not checked because if that fails the 21: * program has scrambled the stack so badly that a sleep() failure is the least 22: * problem the program has. The select() call either completes successfully 23: * or is interrupted - no errors to be checked for. 24: */ 25: 26: u_int 27: sleep(seconds) 28: u_int seconds; 29: { 30: struct timeval f, s; 31: 32: if (seconds) 33: { 34: gettimeofday(&f, NULL); 35: s.tv_sec = seconds; 36: s.tv_usec = 0; 37: select(0, NULL, NULL, NULL, &s); 38: gettimeofday(&s, NULL); 39: seconds -= (s.tv_sec - f.tv_sec); 40: /* 41: * ONLY way this can happen is if the system time gets set back while we're 42: * in the select() call. In this case return 0 instead of a bogus number. 43: */ 44: if (seconds < 0) 45: seconds = 0; 46: } 47: return(seconds); 48: }