1. semcreate程序
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
int main(int argc, char** argv)
{
int c, flags;
sem_t *sem;
unsigned int value;
flags = O_RDWR | O_CREAT;
value = 1;
while((c = getopt(argc, argv, "e:")) != -1)
{
switch(c)
{
case 'e':
flags != O_EXCL;
break;
case 'i':
value = atoi(optarg);
break;
}
}
if(optind != argc - 1)
{
printf("usage: semcreate [ -e ] [ -i initalvalue] <name> ");
}
sem = sem_open(argv[optind], flags, FILE_MODE, value);
sem_close(sem);
exit(0);
}
2. semunlink程序
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("usage: semunlink <name>");
}
sem_unlink(argv[1]);
exit(0);
}
3. semgetvalue程序
#include <unistd.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
sem_t *sem;
int value;
if(argc != 2)
{
printf("usage: semgetvalue <name>");
}
sem = sem_open(argv[1], 0);
sem_getvalue(sem, &value);
printf("value = %d\n", value);
exit(0);
}
4.semwait程序
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
sem_t* sem;
int value;
if(argc != 2)
{
printf("usage: semwait <name>");
}
sem = sem_open(argv[1], 0);
sem_wait(sem);
sem_getvalue(sem, &value);
printf("pid %ld has semaphore, value = %d\n", (long)getpid(), value);
pause();
exit(0);
}
5.sempost程序
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
sem_t* sem;
int val;
if(argc != 2)
{
printf("usage: sempost <name>");
}
sem = sem_open(argv[1], 0);
sem_post(sem);
sem_getvalue(sem, &val);
printf("value = %d\n", val);
exit(0);
}