Advertisement
LeonidR

Shot

Dec 5th, 2013
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. //open
  6. #include <fcntl.h>
  7.  
  8. //read, write
  9. #include <unistd.h>
  10.  
  11. //signal
  12. #include <signal.h>
  13.  
  14. #define INPIPE "shotPipeOut"
  15. #define OUTPIPE "shotPipeIn"
  16. typedef struct _coo{
  17.     int x;
  18.     int y;
  19. } coo;
  20.  
  21. void safeClose(){
  22.     unlink(INPIPE);
  23.     unlink(OUTPIPE);
  24.     exit(1);
  25. }
  26.  
  27. int main(){
  28.     signal(SIGINT, safeClose); //se mi fermano con ctrl-c rimuovo le pipe
  29.  
  30.     //Creazione mirino, posizione iniziale (0,0)
  31.     coo mirino;
  32.     mirino.x = 0;
  33.     mirino.y = 0;
  34.  
  35.     //creo le due pipe
  36.     mkfifo(INPIPE, 0666);
  37.     mkfifo(OUTPIPE, 0666);
  38.  
  39.     int fd0, fd1;
  40.     //apro le due pipe
  41.     if(((fd0 = open(INPIPE, O_RDWR)) < 0) || ((fd1 = open(OUTPIPE, O_RDWR)) < 0)){
  42.         perror("Errore apertura pipe");
  43.         exit(1);
  44.     }
  45.  
  46.     int i;
  47.     char leggi[10];
  48.     char risposta[10];
  49.  
  50.    
  51.     int j = 0;
  52.     while(j++ < 10){
  53.         i = 0;
  54.         //accumulo la stringa
  55.         while((i < 10) && read(fd0, &leggi[i], 1) && (leggi[i++] != '#'));
  56.  
  57.         coo bersaglio;
  58.         sscanf(leggi, "%d,%d", &(bersaglio.x), &(bersaglio.y));
  59.  
  60.         coo spostamento;
  61.         spostamento.x = bersaglio.x - mirino.x;
  62.         spostamento.y = bersaglio.y - mirino.y;
  63.  
  64.         mirino.x = bersaglio.x;
  65.         mirino.y = bersaglio.y;
  66.  
  67.         sprintf(risposta, "%d,%d#", spostamento.x, spostamento.y);
  68.         printf("%s\n", risposta);
  69.         write(fd1, risposta, strlen(risposta));
  70.     }
  71.  
  72.     unlink(INPIPE);
  73.     unlink(OUTPIPE);
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement