Programação do sistema Linux 65 processos, matriz de 3 semáforos de comunicação entre threads

NAME
       semget - get a System V semaphore set identifier :
创建一个新的信号量或获取一个已经存在的信号量的ID

SYNOPSIS
       #include <sys/types.h>
       #include <sys/ipc.h>
       #include <sys/sem.h>

/ *
chave:
Se a criação e aquisição do processo não relacionado é a mesma que a fila de mensagens anterior.
Se no processo relacionado, após fork (), cada processo filho pode obter o valor da chave criado pelo processo pai. Neste momento , você não se preocupa mais com o valor da chave. Neste momento, você pode defini-lo como IPC_PRIVATE, o que significa que o IPC é um IPC anônimo e não requer ftok.

nsems: Especifique quantos elementos na matriz de semáforo atual
semflg: outros requisitos especiais, quando a chave é IPC_PRIVATE, semflg é definido como IPC_CREAT

* /

int semget(key_t key, int nsems, int semflg);


RETURN VALUE
       If successful, the return value will be the semaphore set identifier (a nonnegative integer), otherwise, -1 is returned, with errno indicating the error.

NAME
       semctl - System V semaphore control operations 
		对目标信号量执行各类操作,不过最常用的是删除它。
SYNOPSIS
       #include <sys/types.h>
       #include <sys/ipc.h>
       #include <sys/sem.h>

/ *
semid: IPC ID
semnum: o valor subscrito do semáforo de destino na matriz
cmd: comando

...
IPC_RMID:从系统中删除目标信号量集合
......
SETVAL:设置数组中下标为semnum的成员值,即设置某个信号量的资源量
......

最后参数:初始值,即资源总量


//设置ID为semid的信号量集合数组中 第1个信号量的资源总量为1
semctl(semid,0,SETVAL,1):

* /

   int semctl(int semid, int semnum, int cmd, ...);

VALORES DE RETORNO
Em caso de falha, semctl () retorna -1 com errno indicando o erro.
Caso contrário, a chamada do sistema retorna um valor não negativo, dependendo do cmd da seguinte maneira:


coleção de semáforo de operação semop ()

NAME
       semop, semtimedop - System V semaphore operations

SYNOPSIS
       #include <sys/types.h>
       #include <sys/ipc.h>
       #include <sys/sem.h>

	/*
semid:目标IPC ID
sops :结构体数组地址
nsops:每个结构体大小
*/
       int semop(int semid, struct sembuf *sops, size_t nsops);

Os elementos dessa estrutura são do tipo struct sembuf, contendo os seguintes membros:

		信号量编号,当使用单个信号量时候,为0
       unsigned short sem_num; 
       信号量操作,取值为-1,表示P操作。归还为+1,为释放操作
       short          sem_op;  
       short          sem_flg;  /* operation flags */

VALORES DE RETORNO
Se for bem sucedido, semop () e semtimedop () retornam 0; caso contrário, eles retornam -1 com errno indicando o erro.

ERROS
Em caso de falha, errno é definido como um dos seguintes:

   E2BIG  The argument nsops is greater than SEMOPM, the maximum number of operations allowed per system call.

   EACCES The calling process does not have the permissions required to perform the specified semaphore operations, and does not have the CAP_IPC_OWNER capability.

   EAGAIN 假错

   EFAULT An address specified in either the sops or the timeout argument isn't accessible.

   EFBIG  For some operation the value of sem_num is less than 0 or greater than or equal to the number of semaphores in the set.

   EIDRM  The semaphore set was removed.

   EINTR  While blocked in this system call, the thread caught a signal; see signal(7).

   EINVAL The semaphore set doesn't exist, or semid is less than zero, or nsops has a nonpositive value.

   ENOMEM The sem_flg of some operation specified SEM_UNDO and the system does not have enough memory to allocate the undo structure.

   ERANGE For some operation sem_op+semval is greater than SEMVMX, the implementation dependent maximum value for semval.

Experiência: uso de semáforo, 20 processos gravam o mesmo arquivo, há apenas um semáforo no semáforo definido nesta rotina e sua função é semelhante à de um mutex.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

#define PROCNUM 20
#define FNAME "/home/mhr/Desktop/xitongbiancheng/super_io/out"
#define LINESIZE 1024
static 	int semid;

//取资源量
static void P(void)
{
	struct sembuf op;
	
	op.sem_num = 0;
	op.sem_op = -1;
	op.sem_flg = 0;

	while(semop(semid,&op,1) < 0)
	{
		if(errno != EINTR || error != EAGAIN)
		{
			perror("semop()");
			exit(1);
		}
	}
}

//归还资源量
static void V(void)
{
	struct sembuf op;
	
	op.sem_num = 0;
	op.sem_op = -1;
	op.sem_flg = 0;

	if(semop(semid,&op,1) < 0)
	{
		perror("semop()");
		exit(1);

	}
}

static void func_add(void)
{
	FILE *fp;
	int fd;
	char linebuf[LINESIZE];

	fp = fopen(FNAME,"r+");
	if(fp == NULL)
	{
		perror("fopen()");
		exit(1);
	}



P();//取资源量
	fgets(linebuf,LINESIZE,fp);
	fseek(fp,0,SEEK_SET);

	//sleep(1);	
	
	fprintf(fp,"%d\n",atoi(linebuf)+1);
	fflush(fp);
V();//归还资源量
	
	fclose(fp);
return;

} 

int main()
{
	int i,err;
	pid_t pid;

//创建信号量数组 IPC 返回值为id
	semid = semget(IPC_PRIVATE,1,IPC_CREAT);
	if(semid < 0)
	{
		perror("semget");
		exir(0);
	}

// 设置信号量集合中 第一个信号量的资源总量为1
	if(semctl(semid,0,SETVAL,1) < 0)
	{
		perror("semctl");
		exir(0);	
	}

	for(i = 0; i < PROCNUM; i++)
	{
		pid = fork();
		if(pid < 0)
		{
			perror("fork()");
			exit(1);
		}
		
		if(pid == 0)//Child 
		{
			func_add();
			exit(0);
		}

	}


	for(i = 0;i < PROCNUM; i++)
	{
		wait(NULL);
	}
	
	//从当前系统 删除该 信号量集合
	semctl(semid,0,IPC_RMID);

	exit(0);
	
}

Acho que você gosta

Origin blog.csdn.net/LinuxArmbiggod/article/details/114849643
Recomendado
Clasificación