Advertisement
NovaYoshi

IPC with pipes

Feb 7th, 2015
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. /*
  2.  * SparklesChat
  3.  *
  4.  * Copyright (C) 2014-2015 NovaSquirrel
  5.  *
  6.  * This program is free software: you can redistribute it and/or
  7.  * modify it under the terms of the GNU General Public License as
  8.  * published by the Free Software Foundation; either version 2 of the
  9.  * License, or (at your option) any later version.
  10.  *
  11.  * This program is distributed in the hope that it will be useful, but
  12.  * WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14.  * General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  */
  19. #include "chat.h"
  20.  
  21. void IPC_New(IPC_Holder *IPC, int Size) {
  22. #ifdef _WIN32
  23.   _pipe(IPC->Pipe, Size, 0);
  24. #else
  25.   pipe(IPC->Pipe);
  26. #endif
  27.   SDL_AtomicSet(&IPC->Ready, 0);
  28. }
  29.  
  30. void IPC_Free(IPC_Holder *IPC) {
  31.   close(IPC->Pipe[0]);
  32.   close(IPC->Pipe[1]);
  33. }
  34.  
  35. void IPC_Write(IPC_Holder *IPC, const char *Text) {
  36.   char *Clone = StringClone(Text);
  37.   write(IPC->Pipe[PIPE_WRITE], &Clone, sizeof(char *));
  38.   SDL_AtomicAdd(&IPC->Ready, 1);
  39. }
  40.  
  41. void IPC_WriteF(IPC_Holder *IPC, const char *format, ...) {
  42.   va_list args;
  43.   char *buf;
  44.   va_start(args, format);
  45.   buf = strdup_vprintf(format, args);
  46.   va_end(args);
  47.   IPC_Write(IPC, buf);
  48.   free(buf);
  49. }
  50.  
  51. char *IPC_Read(int Timeout, int Count, ...) {
  52.   int i;
  53.   IPC_Holder *IPC[Count];
  54.  
  55.   va_list ap;
  56.   va_start(ap, Count);
  57.   for(i=0; i<Count; i++)
  58.     IPC[i] = va_arg(ap, IPC_Holder*);
  59.   va_end(ap);
  60.  
  61.   // alternative strategy because select() doesn't work on pipes on Windows
  62.   int Delay = Timeout / 10;
  63.   for(int Tries = 0; Tries < 10; Tries++) {
  64.     for(i=0; i<Count; i++)
  65.       if(SDL_AtomicGet(&IPC[i]->Ready)) {
  66.         char *String;
  67.         read(IPC[i]->Pipe[PIPE_READ], &String, sizeof(char *));
  68.         SDL_AtomicAdd(&IPC[i]->Ready, -1);
  69.         return String;
  70.       }
  71.     SDL_Delay(Delay);
  72.   }
  73.   return NULL;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement