init.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #define print(str) write(STDERR_FILENO, str, strlen(str))
  6. int main(int argc, char** argv)
  7. {
  8. print("***** GBOS INIT SYSTEM *****\n");
  9. _run_sh:;
  10. pid_t sh_pid = fork();
  11. if (sh_pid < 0) {
  12. print("[init] unable to fork(), exiting...\n");
  13. return -1;
  14. }
  15. // child
  16. if (sh_pid == 0) {
  17. pid_t sid = setsid();
  18. if (sid < 0) {
  19. print("[init] unable to setsid, exiting...\n");
  20. return -1;
  21. }
  22. char* shell_argv[128] = {};
  23. char* envp[1] = { NULL };
  24. if (argc < 2)
  25. shell_argv[0] = "/bin/sh";
  26. else
  27. shell_argv[0] = argv[1];
  28. for (int i = 2; i < argc; ++i)
  29. shell_argv[i - 1] = argv[i];
  30. execve(shell_argv[0], shell_argv, envp);
  31. print("[init] unable to run sh, exiting...\n");
  32. return -1;
  33. }
  34. int ret, pid;
  35. char buf[512] = {};
  36. for (;;) {
  37. pid = wait(&ret);
  38. snprintf(buf, sizeof(buf), "[init] pid%d has exited with code %d\n", pid, ret);
  39. print(buf);
  40. // sh
  41. if (pid == sh_pid)
  42. goto _run_sh;
  43. }
  44. return 0;
  45. }