#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/mman.h>
#define COUNTNO 20
sem_t sem;
sem_t *psem = NULL;
int main(int argc, char *argv[])
{
int pid,i;
int val;
//記憶體映射實作信号量共享
psem = (sem_t *)mmap(NULL, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -, );
if (psem == NULL)
{
printf("Share memory failed!\n");
return -;
}
if (sem_init(psem, , ) == -)
{
printf("Init unamed sem failed!\n");
return -;
}
sem_getvalue(psem,&val);
printf("this is the main function the psem value is %d\n",val);
pid = fork();
if(pid==){
for (i=;i<COUNTNO;i++)
{
//sem_wait(psem); //相當于P操作
sleep();
sem_getvalue(psem,&val);
printf("this is child,the count num is %d\n",i);
sem_post(psem); //相當于V操作
}
}
else {
for (i=;i<COUNTNO;i++)
{
sem_wait(psem);
sem_getvalue(psem,&val);
printf("this is father,the sem count num is %d\n",i);
//sem_post(psem);
}
}
sem_destroy(psem);
return ;
}