aboutsummaryrefslogtreecommitdiff
path: root/popen.c
blob: 74ccd0e8bbddd4d9eb01448ee4bd00c8712df9f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* :popen: for PD - windows + linux + (probably mac) - carmen rocco */

#include <m_pd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define INBUFSIZE 1024

static t_class *popen_class;

typedef struct _popen
{
     t_object x_obj;
     char buffer[128];
     t_symbol *x_s;
     t_outlet* x_done;
} t_popen;

static void popen_out(t_popen* x)
{
  int i;
  int size = 0;
  size = strlen(x->buffer);
  for (i=0;i<size;i++)
    if (x->buffer[i] == '\n' || x->buffer[i] == '\r') x->buffer[i] = '\0';
  fprintf(stderr, "%s",x->buffer);
  x->x_s = gensym(x->buffer);
  outlet_symbol(x->x_obj.ob_outlet, x->x_s); 
}

static void popen_anything(t_popen *x, t_symbol *s, int argc, t_atom *argv)
{
  int i;
  char arg[MAXPDSTRING];
  char cmd[MAXPDSTRING] = "";
  FILE *pPipe;
  int size = 0;
  for (i=0;i<argc;i++) {
    atom_string(argv,arg+size,MAXPDSTRING - size);
    argv++;
    size=strlen(arg);
    arg[size++] = ' ';
  }
  arg[size-1] = '\0';

  strcat(cmd, s->s_name);
  strcat(cmd, " ");
  strcat(cmd, arg);
  post("sending %s",cmd);

#ifdef _WIN32
  if( (pPipe = _popen( cmd, "rt" )) == NULL )
#else
  if( (pPipe = popen( cmd, "r" )) == NULL )
#endif
    return;

  while( !feof( pPipe ) )
    {
      if( fgets( x->buffer, 128, pPipe ) != NULL )
	popen_out(x);
    }
#ifdef _WIN32
  _pclose( pPipe );
#else
  pclose( pPipe );
#endif

  outlet_bang(x->x_done);
}

void popen_free(t_popen* x)
{
}

static void *popen_new(void)
{
    t_popen *x = (t_popen *)pd_new(popen_class);
    outlet_new(&x->x_obj, &s_symbol);
    x->x_done = outlet_new(&x->x_obj, &s_bang);
    return (x);
}

void popen_setup(void)
{
    popen_class = class_new(gensym("popen"), (t_newmethod)popen_new, 
			    (t_method)popen_free,sizeof(t_popen), 0,0);
    class_addbang(popen_class,popen_out);
    class_addanything(popen_class, popen_anything);
}