I am learning OS and using nachos as an instruction tool. Anyway, here is a question. The following code will lead to a "segmentation fault". Specifically, the program runs well until the thread which prints "D" finishes (reaches the upper limit).
Do you have any idea why? Thanks.
Code:
/* nice_free.c
* Test program to run several threads with different priorities.
* Each thread uses the NICE system call to adjust its static
* priority by various amounts, to influence execution order.
*
* This version of nice does not use the console, it uses a
* debugging system call, Echo, instead.
*/
#include "syscall.h"
#include "stdlib.h"
#define OUTPUT_LOOP_LIMIT 500
#define A_NICE 0
#define B_NICE 5
#define C_NICE 10
#define D_NICE 15
int
main()
{
int a,b,c,d;
int pid;
Echo ("Starting...\n", 12);
pid = Fork();
if (pid == 0)
{
pid = Fork();
if (pid != 0) {
pid = Fork();
if (pid != 0) {
Nice (A_NICE);
for (a = 0; a < OUTPUT_LOOP_LIMIT; a++) {
Echo ("A", 1);
}
Exit (0);
} else {
Nice (B_NICE);
for (b = 0; b < OUTPUT_LOOP_LIMIT; b++) {
Echo ("B", 1);
}
Exit (0);
}
} else {
pid = Fork();
if (pid != 0) {
Nice (C_NICE);
for (c = 0; c < OUTPUT_LOOP_LIMIT; c++) {
Echo ("C", 1);
}
Exit (0);
} else {
Nice (D_NICE);
for (d = 0; d < OUTPUT_LOOP_LIMIT; d++) {
Echo ("D", 1);
}
Exit (0);
}
}
}
/*Original Thread*/
Wait (0);
Echo ("\nFinished\n", 10);
Exit(0); /* and then we're done */
}