(no commit message)
[ptask.git] / src / main.c
1 /*
2  * Copyright (C) 2010-2012 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  */
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <json/json.h>
24
25 static char *task_exec(char *opts)
26 {
27         FILE *f;
28         int ret, s;
29         char *str, *tmp, *cmd, buf[1024];
30
31         str = NULL;
32
33         cmd = malloc(strlen("task rc.json.array=on ") + strlen(opts) + 1);
34         strcpy(cmd, "task rc.json.array=on ");
35         strcat(cmd, opts);
36
37         f = popen(cmd, "r");
38
39         if (!f) {
40                 perror("popen");
41                 goto exit_free;
42         }
43
44         str = malloc(1);
45         str[0] = '\0';
46         while ((s = fread(buf, 1, 1024, f))) {
47                 tmp = malloc(strlen(str) + s + 1);
48                 memcpy(tmp, str, strlen(str));
49                 memcpy(tmp + strlen(str), buf, s);
50                 tmp[strlen(str) + s] = '\0';
51                 free(str);
52                 str = tmp;
53         }
54
55         ret = pclose(f);
56
57         if (ret == -1) {
58                 printf("pclose fails\n");
59                 perror("pclose");
60         }
61
62  exit_free:
63         free(cmd);
64
65         return str;
66 }
67
68 static struct json_object *task_exec_json(char *opts)
69 {
70         struct json_object *o;
71         char *str;
72         
73         str = task_exec(opts);
74
75         if (str) {
76                 o = json_tokener_parse(str);
77                 free(str);
78                 return o;
79         } 
80
81         return NULL;
82 }
83
84 int main(int argc, char **argv)
85 {
86         struct json_object *o;
87
88         o = task_exec_json("export");
89
90         printf("%s\n", json_object_to_json_string(o));
91
92         exit(EXIT_SUCCESS);
93 }