Guest User

Untitled

a guest
Apr 25th, 2014
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. #define TRUNC_AT(str, reject) {\
  7.     size_t s_len = strcspn(str, reject); \
  8.     str[s_len] = '\0';\
  9. }
  10.  
  11. #define TENTRY(x) {cmd[IDX_##x], IDX_##x}
  12.  
  13. #define BUF_SIZE (1024*1024)
  14.  
  15. #define IDX_SKB      0
  16. #define IDX_I3STATUS 1
  17.  
  18. char buf[2][BUF_SIZE] = {"", ""};
  19.  
  20. pthread_mutex_t m;
  21. const char *cmd[] = {
  22.     "/home/dmitriy/bin/skb",
  23.     "/usr/bin/python3 /home/dmitriy/bin/config.py"
  24. };
  25.  
  26. struct tinfo {
  27.     const char *cmd;
  28.     int idx;
  29. };
  30.  
  31. int first = 3;
  32.  
  33. void *callback(void *arg){
  34.     struct tinfo *ti = (struct tinfo *) arg;
  35.     FILE *fd = popen(ti->cmd, "r");
  36.     while (fgets(buf[ti->idx], BUF_SIZE, fd)){
  37.         pthread_mutex_lock(&m);
  38.         if (first) {
  39.             if (ti->idx == IDX_I3STATUS) {
  40.                 printf("%s", buf[ti->idx]);
  41.                 fflush(stdout);
  42.                 first--;
  43.             }
  44.         } else {
  45.             TRUNC_AT(buf[IDX_I3STATUS], "]");
  46.             TRUNC_AT(buf[IDX_SKB], "\n");
  47.             printf("%s,{\"name\": \"lang\", \"full_text\": \"%s\"}]\n",
  48.                     buf[IDX_I3STATUS], buf[IDX_SKB]);
  49.             fflush(stdout);
  50.         }
  51.         pthread_mutex_unlock(&m);
  52.     }
  53.     return NULL;
  54. }
  55.  
  56.  
  57.  
  58. int main(){
  59.     pthread_t t[2];
  60.     struct tinfo ti[2] = {
  61.         TENTRY(SKB),
  62.         TENTRY(I3STATUS)
  63.     };
  64.     pthread_mutex_init(&m, NULL);
  65.     int i;
  66.     for (i = 0; i < 2; i++){
  67.         pthread_create(&t[i], NULL, callback, (void *) &ti[i]);
  68.     }
  69.     for (i = 0; i < 2; i++){
  70.         pthread_join(t[i], NULL);
  71.     }
  72.     pthread_mutex_destroy(&m);
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment