libidav/utils.c

changeset 731
e0358fa1a3b1
parent 723
5ca174b3247a
child 737
1c75c0498520
equal deleted inserted replaced
730:83f832e345e0 731:e0358fa1a3b1
42 #include <conio.h> 42 #include <conio.h>
43 #define getpasswordchar() getch() 43 #define getpasswordchar() getch()
44 #define IS_PATH_SEPARATOR(c) (c == '/' || c == '\\') 44 #define IS_PATH_SEPARATOR(c) (c == '/' || c == '\\')
45 #define PATH_SEPARATOR '\\' 45 #define PATH_SEPARATOR '\\'
46 #else 46 #else
47 #include <unistd.h>
48 #include <spawn.h>
49 #include <sys/wait.h>
47 #include <termios.h> 50 #include <termios.h>
48 #define getpasswordchar() getchar() 51 #define getpasswordchar() getchar()
49 #define IS_PATH_SEPARATOR(c) (c == '/') 52 #define IS_PATH_SEPARATOR(c) (c == '/')
50 #define PATH_SEPARATOR '/' 53 #define PATH_SEPARATOR '/'
51 #endif 54 #endif
1112 char *str = buf->space; 1115 char *str = buf->space;
1113 free(buf); // only free the UcxBuffer struct 1116 free(buf); // only free the UcxBuffer struct
1114 return str; 1117 return str;
1115 } 1118 }
1116 1119
1120 int util_exec_command(char *command, UcxBuffer *outbuf) {
1121 #ifdef _WIN32
1122 fprintf(stderr, "util_exec_command unsupported\n");
1123 return NULL;
1124 #endif
1125
1126 int pout[2];
1127 if(pipe(pout)) {
1128 perror("pipe");
1129 return 1;
1130 }
1131
1132 int ret = 0;
1133
1134 // close stdin and stderr, use pipe for stdout
1135 posix_spawn_file_actions_t actions;
1136 posix_spawn_file_actions_init(&actions);
1137 posix_spawn_file_actions_addclose(&actions, 0);
1138 posix_spawn_file_actions_adddup2(&actions, pout[1], 1);
1139 posix_spawn_file_actions_addclose(&actions, 2);
1140
1141 char *args[4];
1142 args[0] = "sh";
1143 args[1] = "-c";
1144 args[2] = command;
1145 args[3] = NULL;
1146
1147 pid_t pid; // child pid
1148 ret = posix_spawn(&pid, "/bin/sh", &actions, NULL, args, NULL);
1149
1150 close(pout[1]);
1151
1152 if(!ret) {
1153 ssize_t r;
1154 char buf[1024];
1155 while((r = read(pout[0], buf, 1024)) > 0) {
1156 ucx_buffer_write(buf, 1, r, outbuf);
1157 }
1158 }
1159
1160 // wait for child process
1161 ret = 1;
1162 waitpid(pid, &ret, 0);
1163
1164 posix_spawn_file_actions_destroy(&actions);
1165 close(pout[0]);
1166
1167 return ret;
1168 }
1117 1169
1118 char* util_hexstr(const unsigned char *data, size_t len) { 1170 char* util_hexstr(const unsigned char *data, size_t len) {
1119 size_t buflen = 2*len + 4; 1171 size_t buflen = 2*len + 4;
1120 UcxBuffer *buf = ucx_buffer_new(malloc(buflen), buflen + 1, 0); 1172 UcxBuffer *buf = ucx_buffer_new(malloc(buflen), buflen + 1, 0);
1121 for(int i=0;i<len;i++) { 1173 for(int i=0;i<len;i++) {

mercurial