int read_and_exec(int socket) { struct buf_t* buf = buf_new(8049); int pos = buf_readuntil(socket, buf, '\n'); if (pos == -2) return 0; char* buffer = buf->data; buffer[pos] = '\0'; struct execargs_t* arguments[1024]; int k = 0; while (1) { char delim; int argc = count_words(buffer, '|'); if (argc == 0) break; char* argv[argc]; int shift; int i = 0; for (i = 0; i < argc; i++) { delim = '|'; argv[i] = get_word(buffer, &delim, &shift); buffer += shift; } arguments[k] = (struct execargs_t*) malloc(sizeof(struct execargs_t)); *arguments[k] = new_args(argc, argv); shift = get_delim(buffer, '|'); buffer+=shift; k++; } buf->size -= (buffer - (char*) buf->data + 1); runpiped(arguments, k, socket); buf_free(buf); return 0; }
int main() { int exit_code = EXIT_SUCCESS; struct buf_t* buf = buf_new(MAX_SIZE); char s[MAX_SIZE + 1]; if (print_prompt() < 0) { QUIT(EXIT_FAILURE); } ssize_t size; while ((size = buf_getline(STDOUT_FILENO, buf, s, MAX_SIZE))) { if (size < 0) { QUIT(EXIT_FAILURE); } s[size] = 0; char** piped_programs = split(s, '|', 0); if (!piped_programs) { goto ERROR; } char** p; for (p = piped_programs; *p; p++) ; int len = p - piped_programs; execargs_t** programs = malloc(len * sizeof(execargs_t*)); if (!programs) { for (char** p = piped_programs; *p; p++) { free(*p); } free(piped_programs); goto ERROR; } for (int i = 0; i < len; i++) { programs[i] = execargs_parse(piped_programs[i]); if (!programs[i]) { for (int j = 0; j < i; j++) { free(programs[j]); } for (int j = 0; j < len; j++) { free(piped_programs[j]); } free(programs); free(piped_programs); goto ERROR; } } if (runpiped(programs, len) < 0) { goto ERROR; } if (print_prompt() < 0) { QUIT(EXIT_FAILURE); } continue; ERROR: if (print_prompt() < 0) { QUIT(EXIT_FAILURE); } } EXIT: buf_free(buf); return exit_code; }