1. 创建信号量,并利用ipcs -s查看信号量:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int semid;
int nsems = 1;//semaphores nums to create
int flags = 0666; //world read-alter mode
struct sembuf buf; //how semop should behave
//create the semaphore with world read-alter perms
semid = semget(IPC_PRIVATE, nsems, flags);
if(semid < 0)
{
perror("semget");
exit(EXIT_FAILURE);
}
printf("semaphore created: %d\n", semid);
//set up the structure for semop
buf.sem_num = 0; //A single semaphore
buf.sem_flg = IPC_NOWAIT; //don't block
if((semop(semid, &buf, nsems)) < 0)
{
perror("semop");
exit(EXIT_FAILURE);
}
system("ipcs -s");
exi