Jump to content
Sign in to follow this  
wrproject

[C] Sistema envio mensagens utilizando Semáforos e Shared Memory em Linux

Recommended Posts

wrproject

Boas pessoal,há muito que nao postava por aqui,mas arranjei algum tempo pra mostrar-vos um exemplo de um sistema de envio mensagens utilizando Semáforos e Filas de mensagens.

É de relembrar que este código só funciona em linux.

SERVIDOR

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

struct sembuf UP={0,1,0};
struct sembuf DOWN={0,-1,0};
int id;

void _UP()
{

semop(id,&UP,1);

}

void _DOWN()
{

semop(id,&DOWN,1);

}

int main(int argc,char** args)
{

int id_m=shmget(301,100*sizeof(char),0600|IPC_CREAT);
char* str=shmat(id_m,0,0);

id=semget(300,1,0600 | IPC_CREAT);


//inicializar o semaforo a 1
semctl(id,0,SETVAL,0);

while(1)
{


_DOWN();
printf("%s\n",str);


}

return 0;
}

Cliente

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

struct sembuf UP={0,1,0};
struct sembuf DOWN={0,-1,0};
int id;

void _UP()
{

semop(id,&UP,1);

}

void _DOWN()
{

semop(id,&DOWN,1);

}

int main(int argc,char** args)
{
int id_m=shmget(301,100*sizeof(char),0600|IPC_CREAT);
char* str=shmat(id_m,0,0);

id=semget(300,1,0600 | IPC_CREAT);


while(1)
{
printf("mensagem:\n");
gets(str);
_UP();

}
printf("ok\n");



return 0;
}

Para testarem devem executar primeiro o server,que será responsavel por receber e mostrar as mensagens,e de seguida executem o cliente.

Qualquer dúvida/critica é só dizer.  :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.