lua_action.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <stdlib.h>
  2. #include <sys/wait.h>
  3. #include <konf/buf.h>
  4. #include <lub/string.h>
  5. #include "private.h"
  6. static int exec_action(lua_State *L, const char *script)
  7. {
  8. int res = 0;
  9. if ((res = luaL_loadstring(L, script))) {
  10. l_print_error(L, __func__, "load", res);
  11. } else if ((res = lua_pcall(L, 0, 0, 0))) {
  12. l_print_error(L, __func__, "exec", res);
  13. }
  14. lua_gc(L, LUA_GCCOLLECT, 0);
  15. return res;
  16. }
  17. CLISH_PLUGIN_SYM(clish_plugin_lua_action)
  18. {
  19. clish_shell_t *shell = clish_context__get_shell(clish_context);
  20. lua_State *L = clish_shell__get_udata(shell, LUA_UDATA);
  21. konf_buf_t *buf;
  22. pid_t childpid;
  23. int res = 0, origstdout = -1, fd[2];
  24. if (!script) /* Nothing to do */
  25. return (0);
  26. if (!out) /* Handle trivial case */
  27. return exec_action(L, script);
  28. pipe(fd);
  29. if ((childpid = fork()) == -1) {
  30. perror("fork");
  31. return -1;
  32. }
  33. if (childpid == 0) { /* Child */
  34. dup2(fd[1], 1);
  35. close(fd[0]);
  36. close(fd[1]);
  37. exit(exec_action(L, script));
  38. } else { /* Parent */
  39. close(fd[1]);
  40. buf = konf_buf_new(fd[0]);
  41. while(konf_buf_read(buf) > 0);
  42. *out = konf_buf__dup_line(buf);
  43. konf_buf_delete(buf);
  44. close(fd[0]);
  45. }
  46. return WEXITSTATUS(res);
  47. }