init.c 1014 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. pid_t sh_pid = fork();
  10. if (sh_pid < 0) {
  11. print("[init] unable to fork(), exiting...\n");
  12. return -1;
  13. }
  14. // child
  15. if (sh_pid == 0) {
  16. char* shell_argv[128] = {};
  17. char* envp[1] = { NULL };
  18. if (argc < 2)
  19. shell_argv[0] = "/bin/sh";
  20. else
  21. shell_argv[0] = argv[1];
  22. for (int i = 2; i < argc; ++i)
  23. shell_argv[i - 1] = argv[i];
  24. execve(shell_argv[0], shell_argv, envp);
  25. print("[init] unable to run sh, exiting...\n");
  26. return -1;
  27. }
  28. int ret, pid;
  29. char buf[512] = {};
  30. for (;;) {
  31. pid = wait(&ret);
  32. snprintf(buf, sizeof(buf), "[init] pid%d has exited with code %d\n", pid, ret);
  33. print(buf);
  34. }
  35. return 0;
  36. }