So given a process id passed to the system call, I need to return all child process ids. This must be written in C. I have used mproc to get the parent process of a child pid and list all processes from a certain index but cannot make the leap from that to this.
My code:
int do_getchildpids() {
// get pid from parameter
int ppid = m_in.m1_i1;
// Get the child pid of this process
pid_t cpid;
if (cpid == fork()) {
printf("Child pid for ppid %d is %d\n", ppid, getpid());
}
// ** Other attempt at this problem below **
// if mp_parent == ppid then print pid
int idx = 0;
int cpid = mproc[idx].mp_pid;
while (mproc[idx].mp_pid) {
idx++;
}
printf("Searching for children of %d...\n", ppid);
if (pid == 0) {
// for loop that gets the ppid, checks against given ppid
// prints out pid if true
if (cpid) {
// loop through proc table checking if ppid is equal to parameter passed
if (ppid == mproc[mproc[i].mp_parent].mp_pid)
printf("Child pid is %d.\n", getpid());
}
printf("Child pid is: %d.\n", getpid());
} else {
printf("Error, child pid was not set or is -1\n");
}
return 0;
}
This is a very janky solution, but if you're running linux and you want to get the children of a parent process you could use the linux
pgrep
command, either by usingfork()
and execv()
or by a simplesystem()
call. Then pipe the output to a file and read that file's contentsThere's definitely a better way to do this though. Look into if it's possible to call
ps
orpgrep
from a c program.