lua_action.c 1.2 KB

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