fix: The timer sequence stuck in infinite loop after series of delete operation
[lunaix-os.git] / lunaix-os / kernel / lxinit.c
1 #include <hal/cpu.h>
2 #include <lunaix/clock.h>
3 #include <lunaix/keyboard.h>
4 #include <lunaix/lunistd.h>
5 #include <lunaix/mm/kalloc.h>
6 #include <lunaix/mm/vmm.h>
7 #include <lunaix/proc.h>
8 #include <lunaix/spike.h>
9 #include <lunaix/syslog.h>
10 #include <lunaix/timer.h>
11 #include <lunaix/tty/tty.h>
12
13 extern uint8_t __kernel_start;
14
15 LOG_MODULE("INIT")
16
17 // #define FORK_BOMB_DEMO
18 // #define WAIT_DEMO
19
20 void
21 _lxinit_main()
22 {
23 #ifdef FORK_BOMB_DEMO
24     // fork炸弹
25     for (;;) {
26         pid_t p;
27         if ((p = fork())) {
28             kprintf(KDEBUG "Pinkie Pie #%d: FUN!\n", p);
29         }
30     }
31 #endif
32
33     int status;
34 #ifdef WAIT_DEMO
35     // 测试wait
36     kprintf("I am parent, going to fork my child and wait.\n");
37     if (!fork()) {
38         kprintf("I am child, going to sleep for 2 seconds\n");
39         sleep(2);
40         kprintf("I am child, I am about to terminated\n");
41         _exit(1);
42     }
43     pid_t child = wait(&status);
44     kprintf("I am parent, my child (%d) terminated normally with code: %d.\n",
45             child,
46             WEXITSTATUS(status));
47 #endif
48
49     pid_t p = 0;
50
51     if (!fork()) {
52         kprintf("Test no hang!");
53         sleep(12);
54         _exit(0);
55     }
56
57     waitpid(-1, &status, WNOHANG);
58
59     // 这里是就是LunaixOS的第一个进程了!
60     for (size_t i = 0; i < 5; i++) {
61         pid_t pid = 0;
62         if (!(pid = fork())) {
63             sleep(i);
64             if (i == 3) {
65                 i = *(int*)0xdeadc0de; // seg fault!
66             }
67             tty_put_char('0' + i);
68             tty_put_char('\n');
69             _exit(0);
70         }
71         kprintf(KINFO "Forked %d\n", pid);
72     }
73
74     while ((p = wait(&status)) >= 0) {
75         short code = WEXITSTATUS(status);
76         if (WIFEXITED(status)) {
77             kprintf(KINFO "Process %d exited with code %d\n", p, code);
78         } else {
79             kprintf(KWARN "Process %d aborted with code %d\n", p, code);
80         }
81     }
82
83     char buf[64];
84
85     kprintf(KINFO "Hello processes!\n");
86
87     cpu_get_brand(buf);
88     kprintf("CPU: %s\n\n", buf);
89
90     // no lxmalloc here! This can only be used within kernel, but here, we are
91     // in a dedicated process! any access to kernel method must be done via
92     // syscall
93
94     struct kdb_keyinfo_pkt keyevent;
95     while (1) {
96         if (!kbd_recv_key(&keyevent)) {
97             // yield();
98             continue;
99         }
100         if ((keyevent.state & KBD_KEY_FPRESSED) &&
101             (keyevent.keycode & 0xff00) <= KEYPAD) {
102             tty_put_char((char)(keyevent.keycode & 0x00ff));
103             tty_sync_cursor();
104         }
105     }
106
107     spin();
108 }