信号量的创建和删除

你。 提交于 2019-11-30 10:57:37

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");
    exit(EXIT_SUCCESS);
}

2.  清除信号量,并利用ipcs -s查看信号量:

//Manipulate and delete a semaphore

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int semid;
	if(argc != 2)
	{
		puts("USAGE:stl1 <semaphore if>");
		exit(EXIT_FAILURE);
	}
	semid = atoi(argv[1]);

	//remove the semaphore
	if((semctl(semid, 0, IPC_RMID))<0)
	{
		perror("semctl IPC_RMID");
		exit(EXIT_FAILURE);
	}
	else
	{
		puts("semaphore removed");
		system("ipcs -s");
	}
	exit(EXIT_SUCCESS);
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!