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 <getopt.h> 19#include <errno.h> 20#include <semaphore.h> 21 22#include "posixtest.h" 23 24#define SEM_NAME "/tmp/semaphore" 25#define BUF_SIZE 200 26#define DEFAULT_THREADS 5 27 28int main(int argc, char *argv[]) 29{ 30 sem_t *sem_lock; 31 int shared = 1; 32 int value = 1; 33 pid_t pid=0; 34 int i, num=0; 35 char buf[BUF_SIZE]; 36 char *c; 37 38#ifndef _POSIX_SEMAPHORES 39 printf("_POSIX_SEMAPHORES is not defined \n"); 40 return PTS_UNRESOLVED; 41#endif 42 if ( (2 != argc) || (( num = atoi(argv[1])) <= 0)) { 43 fprintf(stdout, "Usage: %s number_of_processes\n", argv[0]); 44 printf("Set num_of_processes to default value %d \n", DEFAULT_THREADS); 45 num = DEFAULT_THREADS; 46 } 47 sem_lock = (sem_t *)malloc(sizeof(sem_t)); 48 if (-1 == sem_init(sem_lock, shared, value)) { 49 perror("sem_init didn't return success\n"); 50 return PTS_UNRESOLVED; 51 } 52 for (i=1; i<num; i++) 53 if ((pid = fork())!=0) 54 { 55 sleep(2); 56 break; 57 } 58 sprintf(buf, "%d process_ID:%ld parent_process_ID:%ld child_process_ID:%ld \n", i, (long)getpid(), (long)getppid(), (long)pid); 59 60 if (-1 == sem_wait(sem_lock)) { 61 perror("sem_wait didn't return success\n"); 62 return PTS_UNRESOLVED; 63 } 64 for (i = 1; i<= 10; i++) { 65 c=buf; 66 while (*c != '\n') { 67 fputc(*c, stdout); 68 c++; 69 } 70 fputc('\n', stdout); 71 } 72 73 if (-1 == sem_post(sem_lock)) { 74 perror("sem_wait didn't return success\n"); 75 return PTS_UNRESOLVED; 76 } 77 78 return PTS_PASS; 79} 80