Home | History | Annotate | Download | only in nanosleep
      1 /*
      2  * Copyright (c) 2002, Intel Corporation. All rights reserved.
      3  * Created by:  julie.n.fleischer REMOVE-THIS AT intel DOT com
      4  * This file is licensed under the GPL license.  For the full content
      5  * of this license, see the COPYING file at the top level of this
      6  * source tree.
      7 
      8  * Test that nanosleep() causes the current thread to be suspended
      9  * until _at least_ the time interval in rqtp passes.
     10  * Test for a variety of time intervals (in nsecs)
     11  */
     12 #include <stdio.h>
     13 #include <time.h>
     14 #include "posixtest.h"
     15 
     16 #define NUMINTERVALS 13
     17 int main(void)
     18 {
     19 	struct timespec tssleepfor, tsstorage, tsbefore, tsafter;
     20 	int sleepnsec[NUMINTERVALS] = { 1, 2, 10, 100, 1000, 10000, 1000000,
     21 		10000000, 100000000, 200000000, 500000000, 750000000,
     22 		999999900
     23 	};
     24 	int i;
     25 	int failure = 0;
     26 	int slepts, sleptns;
     27 
     28 	if (clock_gettime(CLOCK_REALTIME, &tsbefore) == -1) {
     29 		perror("Error in clock_gettime()\n");
     30 		return PTS_UNRESOLVED;
     31 	}
     32 
     33 	tssleepfor.tv_sec = 0;
     34 	for (i = 0; i < NUMINTERVALS; i++) {
     35 		tssleepfor.tv_nsec = sleepnsec[i];
     36 		if (nanosleep(&tssleepfor, &tsstorage) != 0) {
     37 			printf("nanosleep() did not return success\n");
     38 			return PTS_UNRESOLVED;
     39 		}
     40 
     41 		if (clock_gettime(CLOCK_REALTIME, &tsafter) == -1) {
     42 			perror("Error in clock_gettime()\n");
     43 			return PTS_UNRESOLVED;
     44 		}
     45 
     46 		/*
     47 		 * Generic alg for calculating slept time.
     48 		 */
     49 		slepts = tsafter.tv_sec - tsbefore.tv_sec;
     50 		sleptns = tsafter.tv_nsec - tsbefore.tv_nsec;
     51 		if (sleptns < 0) {
     52 			sleptns = sleptns + 1000000000;
     53 			slepts = slepts - 1;
     54 		}
     55 
     56 		if (slepts >= 1 || sleptns > sleepnsec[i]) {
     57 			printf("PASS slept %ds %dns >= %d\n",
     58 			       slepts, sleptns, sleepnsec[i]);
     59 		} else {
     60 			printf("FAIL slept %ds %dns < %d\n",
     61 			       slepts, sleptns, sleepnsec[i]);
     62 			failure = 1;
     63 		}
     64 	}
     65 
     66 	if (failure) {
     67 		printf("At least one test FAILED\n");
     68 		return PTS_FAIL;
     69 	}
     70 
     71 	printf("All tests PASSED\n");
     72 	return PTS_PASS;
     73 }
     74