• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* named semaphore sanity check */
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <semaphore.h>
7 #include <time.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include "test.h"
11 
12 #define TEST(c, ...) \
13 	( (c) || (t_error(#c " failed: " __VA_ARGS__),0) )
14 
main(void)15 int main(void)
16 {
17 	char buf[100];
18 	struct timespec ts;
19 	sem_t *sem, *sem2;
20 	int val;
21 
22 	clock_gettime(CLOCK_REALTIME, &ts);
23 	snprintf(buf, sizeof buf, "/testsuite-%d-%d", (int)getpid(), (int)ts.tv_nsec);
24 
25 	TEST((sem=sem_open(buf, O_CREAT|O_EXCL, 0700, 1)) != SEM_FAILED,
26 		"could not open sem: %s\n", strerror(errno));
27 	errno = 0;
28 	TEST(sem_open(buf, O_CREAT|O_EXCL, 0700, 1) == SEM_FAILED,
29 		"reopening should fail with O_EXCL\n");
30 	TEST(errno == EEXIST,
31 		"after reopen failure errno is \"%s\" (%d); want EEXIST (%d)\n", strerror(errno), errno, EEXIST);
32 
33 	TEST(sem_getvalue(sem, &val) == 0, "failed to get sem value\n");
34 	TEST(val == 1, "wrong initial semaphore value: %d\n", val);
35 
36 	TEST((sem2=sem_open(buf, 0)) == sem,
37 		"could not reopen sem: got %p, want %p\n", sem2, sem);
38 
39 	errno = 0;
40 	TEST(sem_wait(sem) == 0, "%s\n", strerror(errno));
41 	TEST(sem_getvalue(sem2, &val) == 0, "%s\n", strerror(errno));
42 	TEST(val == 0, "wrong semaphore value on second handle: %d\n", val);
43 
44 	errno = 0;
45 	TEST(sem_trywait(sem) == -1 && errno == EAGAIN,
46 		"trywait on locked sem: got errno \"%s\" (%d), want EAGAIN (%d)\n", strerror(errno), errno, EAGAIN);
47 
48 	TEST(sem_post(sem) == 0, "%s\n", strerror(errno));
49 	TEST(sem_getvalue(sem2, &val) == 0, "%s\n", strerror(errno));
50 	TEST(val == 1, "wrong semaphore value on second handle: %d\n", val);
51 
52 	TEST(sem_close(sem) == 0, "%s\n", strerror(errno));
53 	TEST(sem_close(sem) == 0, "%s\n", strerror(errno));
54 	TEST(sem_unlink(buf) == 0, "%s\n", strerror(errno));
55 	return t_status;
56 }
57