/*
 * $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred."
 *
 */
/*	Copyright (c) 1984 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

#ident	"@(#)libc-port:gen/sleep.c	1.11"
/*	3.0 SID #	1.4	*/
/*LINTLIBRARY*/
/*
 * Suspend the process for `sleep_tm' seconds - using alarm/sigpause
 * system calls.  If caller had an alarm already set to go off `n'
 * seconds from now, then Case 1: (sleep_tm >= n) sleep for n, and
 * cause the callers previously specified alarm interrupt routine
 * to be executed, then return the value (sleep_tm - n) to the caller
 * as the unslept amount of time, Case 2: (sleep_tm < n) sleep for
 * sleep_tm, after which, reset alarm to go off when it would have
 * anyway.  In case process is aroused during sleep by any caught
 * signal, then reset any prior alarm, as above, and return to the
 * caller the (unsigned) quantity of (requested) seconds unslept.
 */
#include <signal.h>
#include <setjmp.h>

extern int pause();
extern unsigned alarm();

unsigned
sleep(sleep_tm)
unsigned sleep_tm;
{
	int  alrm_flg;
	void awake();
	struct sigaction sa, old_sa;
	sigset_t alarm_set, temp_set, old_set;
	unsigned unslept, alrm_tm, left_ovr;

	if(sleep_tm == 0)
		return(0);

	(void) sigemptyset(&alarm_set);
	sa.sa_mask = alarm_set;
	sa.sa_flags = 0;
	sa.sa_handler = awake;
	(void) sigaddset(&alarm_set, SIGALRM);
	(void) sigprocmask(SIG_BLOCK, &alarm_set, &old_set);
	temp_set = old_set;
	(void) sigdelset(&temp_set, SIGALRM);
	(void) sigaction(SIGALRM, &sa, &old_sa);
	alrm_tm = alarm(0);			/* prev. alarm time */

	alrm_flg = 0;
	left_ovr = 0;

	if(alrm_tm != 0) {	/* skip all this if no prev. alarm */
		if(alrm_tm > sleep_tm) {	/* alarm set way-out */
			alrm_tm -= sleep_tm;
			++alrm_flg;
		} else {	/* alarm will shorten sleep time */
			left_ovr = sleep_tm - alrm_tm;
			sleep_tm = alrm_tm;
			alrm_tm = 0;
			--alrm_flg;
			(void) sigaction(SIGALRM, &old_sa, 0);
		}
	}

	alarm(sleep_tm);
	(void) sigsuspend(&temp_set);

	unslept = alarm(0);
	/* clear pending signal */
	(void) sigprocmask(SIG_BLOCK, &alarm_set, 0);
	(void) sigprocmask(SIG_UNBLOCK, &alarm_set, 0);
	if(alrm_flg >= 0)
		(void) sigaction(SIGALRM, &old_sa, 0);
	if(alrm_flg > 0 || (alrm_flg < 0 && unslept != 0))
		(void) alarm(alrm_tm + unslept);
	(void) sigprocmask(SIG_SETMASK, &old_set, 0);
	return(left_ovr + unslept);
}

static void
awake() {
	return;
}
