So I want to write recursive syscall in c which gets all descendands from a process (kids, grandkids, ..). System which I'm using is Minix 3.2.1, but I don't think it should be much different from most UNIX systems. However my function throws very ugly error. The code is as follows:
int do_whoMaxDescendants(void)
{
int maxChildren = 0;
pid_t found = -1;
for (int proc_nr = 0; proc_nr < NR_PROCS; proc_nr)
{
if (mproc[proc_nr].mp_flags & IN_USE)
{
int children = kidCount(proc_nr);
if (children > maxChildren)
{
maxChildren = children;
found = mproc[proc_nr].mp_pid;
}
}
}
return found;
}
int kidCount(int currParent)
{
int children = 0;
for (int nextParent = 0; nextParent < NR_PROCS; nextParent)
{
if ((mproc[nextParent].mp_flags & IN_USE) && (mproc[nextParent].mp_parent == currParent))
{
children ;
children = kidCount(nextParent) children;
}
}
return children;
}
And the error looks like this:
CodePudding user response:
You are writing Minix kernel code. The Minix kernel stack is 4096 bytes. Any significant recursion is likely to overflow it, and that's probably the cause of your page fault. Note the faulting address is near the end of a page, probably the next page below the stack page, which may be an unmapped guard page so that a stack overflow panics before corrupting other data.
So you will need to come up with an algorithm that doesn't use recursion.