Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/wait.h> // wait
- #include <stdlib.h> //exit
- #include <fcntl.h>
- #include <string.h>
- #include <sys/mman.h>
- #include <time.h>
- #include <semaphore.h>
- #define N_VOTOS 10000
- #define N_PROCESSOS 10
- typedef struct {
- char mocao[256];
- char votacao[N_VOTOS];
- int countS;
- int countN;
- }votos;
- int main(int argc, char **argv){
- char voto;
- int fd, i, j;
- votos *v;
- sem_t *mutex, *vot;
- if((vot = sem_open("vot", O_EXCL, 0644, 0)) == SEM_FAILED) {
- vot = sem_open("vot", O_CREAT|O_EXCL, 0644, 0);
- printf("Bem-vindo sócio nº %s\n", argv[1]);
- printf("À espera de uma votação...\n\n");
- sem_wait(vot);
- sem_post(vot);
- }else{
- printf("Bem-vindo sócio nº %s\n", argv[1]);
- }
- if((mutex = sem_open("mutex", O_EXCL, 0644, 1)) == SEM_FAILED) {
- perror("No sem_open() mutex");
- exit(1);
- }else{
- fd = shm_open("/votos", O_RDWR,S_IRUSR|S_IWUSR);
- ftruncate(fd, sizeof(votos));
- v = (votos *) mmap(NULL,sizeof(votos),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
- if(argc == 1) {
- printf("Número inválido de argumentos, inclua o seu número de sócio.\n");
- exit(1);
- }else{
- if(argc > 2) {
- printf("Demasiados argumentos!\n");
- }else{
- if((atoi(argv[1]) >= 10000) || (atoi(argv[1]) < 0)) {
- printf("Número de sócio inválido!\n");
- exit(1);
- }
- sem_wait(mutex);
- printf("Votação Iniciada, Moção: %s\n", v->mocao);
- sem_post(mutex);
- printf("Qual o seu voto? (S/N)\n");
- scanf(" %c", &voto);
- if(voto == 'S') {
- printf("Voto válido.\n");
- }else{
- if(voto == 'N') {
- printf("Voto válido.\n");
- }else{
- printf("Voto Inválido!\n");
- exit(1);
- }
- }
- sem_wait(mutex);
- v->votacao[atoi(argv[1])] = voto;
- sem_post(mutex);
- }
- }
- }
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement