1 | /*␊ |
2 | * shell_process.cpp␊ |
3 | *␊ |
4 | * Created by Rekursor on 1/17/2010.␊ |
5 | *␊ |
6 | */␊ |
7 | ␊ |
8 | #include "ShellProcess.h"␊ |
9 | #include <string.h>␊ |
10 | #include <sys/stat.h>␊ |
11 | #include "string_util.h"␊ |
12 | ␊ |
13 | #define MAX_LINESIZE 4096␊ |
14 | ␊ |
15 | //----------------------------------------------------------------␊ |
16 | // portable open process:␊ |
17 | FILE * ShellProcess::open(const char *cmd, const char *mode) {␊ |
18 | ␉_fpt=::popen(cmd,mode);␊ |
19 | ␉return _fpt;␊ |
20 | }␊ |
21 | ␊ |
22 | //----------------------------------------------------------------␊ |
23 | int ShellProcess::close() {␊ |
24 | ␉int ret = ::pclose(_fpt);␊ |
25 | ␉_fpt=NULL;␊ |
26 | ␉return ret;␊ |
27 | }␊ |
28 | ␊ |
29 | //----------------------------------------------------------------␊ |
30 | std::string ShellProcess::get_line(const char * matching)␊ |
31 | {␊ |
32 | char buffer[MAX_LINESIZE];␊ |
33 | ␊ |
34 | char* res = get_line(buffer, MAX_LINESIZE-1, matching);␊ |
35 | std::string result = res ? res : "";␊ |
36 | ␊ |
37 | return result;␊ |
38 | }␊ |
39 | //----------------------------------------------------------------␊ |
40 | char * ShellProcess::get_line(char * line, size_t s, const char *matching)␊ |
41 | {␊ |
42 | ␉if (_fpt==NULL || line==NULL) return NULL;␊ |
43 | ␉char * l = fgets(line, s, _fpt);␊ |
44 | ␉␊ |
45 | ␉if (matching==NULL || (*matching)=='\0') ␊ |
46 | ␉␉return l; // we're done␊ |
47 | ␉␊ |
48 | ␉// search first line matching substring 'matching'␊ |
49 | ␉size_t len = strlen(line);␊ |
50 | ␉␊ |
51 | ␉for (; l!=NULL && (len >0) ;)␊ |
52 | ␉{␊ |
53 | ␉␉if (strstr(line, matching))␊ |
54 | ␉␉{␊ |
55 | ␉␉␉return l;␊ |
56 | ␉␉}␊ |
57 | ␉␉␊ |
58 | ␉␉*line = '\0';␊ |
59 | ␉␉l = fgets(line, s, _fpt);␊ |
60 | ␉␉len = strlen(line);␊ |
61 | ␉}␊ |
62 | ␉␊ |
63 | ␉return l;␊ |
64 | }␊ |
65 | |