1 /*
2 * Copyright (c) 2002, Intel Corporation. All rights reserved.
3 * Created by: crystal.xiong 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 * This test use semaphore to protect critical section between several
9 * processes.
10 */
11 #include <stdio.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14 #include <stdlib.h>
15 #include <sys/wait.h>
16 #include <sys/mman.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <semaphore.h>
20
21 #include "posixtest.h"
22
23 #define SEM_NAME "/tmp/semaphore"
24 #define BUF_SIZE 200
25 #define DEFAULT_THREADS 5
26
main(int argc,char * argv[])27 int main(int argc, char *argv[])
28 {
29 sem_t *sem_lock;
30 int shared = 1;
31 int value = 1;
32 pid_t pid = 0;
33 int i, num = 0;
34 char buf[BUF_SIZE];
35 char *c;
36
37 #ifndef _POSIX_SEMAPHORES
38 printf("_POSIX_SEMAPHORES is not defined \n");
39 return PTS_UNRESOLVED;
40 #endif
41 if ((2 != argc) || ((num = atoi(argv[1])) <= 0)) {
42 printf("Setting num_of_processes to default value: %d\n",
43 DEFAULT_THREADS);
44 num = DEFAULT_THREADS;
45 }
46 if ((sem_lock = malloc(sizeof(sem_t))) == NULL) {
47 perror("malloc");
48 return PTS_UNRESOLVED;
49 }
50 if (sem_init(sem_lock, shared, value) == -1) {
51 perror("sem_init didn't return success\n");
52 return PTS_UNRESOLVED;
53 }
54 for (i = 1; i < num; i++)
55 switch ((pid = fork())) {
56 case -1:
57 perror("fork");
58 return PTS_UNRESOLVED;
59 case 0:
60 break;
61 default:
62 sleep(2);
63 break;
64 }
65
66 sprintf(buf, "%d process_ID: %ld parent_process_ID: %ld "
67 "child_process_ID: %ld\n", i, (long)getpid(),
68 (long)getppid(), (long)pid);
69
70 if (sem_wait(sem_lock) == -1) {
71 perror("sem_wait didn't return success\n");
72 return PTS_UNRESOLVED;
73 }
74 for (i = 1; i <= 10; i++) {
75 c = buf;
76 while (*c != '\n') {
77 fputc(*c, stdout);
78 c++;
79 }
80 fputc('\n', stdout);
81 }
82
83 if (sem_post(sem_lock) == -1) {
84 perror("sem_wait didn't return success\n");
85 return PTS_UNRESOLVED;
86 }
87
88 return PTS_PASS;
89 }
90