Advertisement
Guest User

VotaSocio.c

a guest
May 24th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h> // wait
  5. #include <stdlib.h> //exit
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <sys/mman.h>
  9. #include <time.h>
  10. #include <semaphore.h>
  11.  
  12. #define N_VOTOS 10000
  13. #define N_PROCESSOS 10
  14.  
  15. typedef struct {
  16. char mocao[256];
  17. char votacao[N_VOTOS];
  18. int countS;
  19. int countN;
  20. }votos;
  21.  
  22. int main(int argc, char **argv){
  23.  
  24. char voto;
  25. int fd, i, j;
  26. votos *v;
  27. sem_t *mutex, *vot;
  28.  
  29. if((vot = sem_open("vot", O_EXCL, 0644, 0)) == SEM_FAILED) {
  30. vot = sem_open("vot", O_CREAT|O_EXCL, 0644, 0);
  31. printf("Bem-vindo sócio nº %s\n", argv[1]);
  32. printf("À espera de uma votação...\n\n");
  33. sem_wait(vot);
  34. sem_post(vot);
  35. }else{
  36. printf("Bem-vindo sócio nº %s\n", argv[1]);
  37. }
  38. if((mutex = sem_open("mutex", O_EXCL, 0644, 1)) == SEM_FAILED) {
  39. perror("No sem_open() mutex");
  40. exit(1);
  41. }else{
  42. fd = shm_open("/votos", O_RDWR,S_IRUSR|S_IWUSR);
  43. ftruncate(fd, sizeof(votos));
  44. v = (votos *) mmap(NULL,sizeof(votos),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  45.  
  46. if(argc == 1) {
  47. printf("Número inválido de argumentos, inclua o seu número de sócio.\n");
  48. exit(1);
  49. }else{
  50. if(argc > 2) {
  51. printf("Demasiados argumentos!\n");
  52. }else{
  53. if((atoi(argv[1]) >= 10000) || (atoi(argv[1]) < 0)) {
  54. printf("Número de sócio inválido!\n");
  55. exit(1);
  56. }
  57. sem_wait(mutex);
  58. printf("Votação Iniciada, Moção: %s\n", v->mocao);
  59. sem_post(mutex);
  60.  
  61. printf("Qual o seu voto? (S/N)\n");
  62. scanf(" %c", &voto);
  63. if(voto == 'S') {
  64. printf("Voto válido.\n");
  65. }else{
  66. if(voto == 'N') {
  67. printf("Voto válido.\n");
  68. }else{
  69. printf("Voto Inválido!\n");
  70. exit(1);
  71. }
  72. }
  73. sem_wait(mutex);
  74. v->votacao[atoi(argv[1])] = voto;
  75. sem_post(mutex);
  76. }
  77. }
  78.  
  79. }
  80. exit(0);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement