C program to get child process id's from just a parent id (minix)

1.3k views Asked by At

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;
}
1

There are 1 answers

0
awerchniak On

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 using fork() and execv() or by a simple system() call. Then pipe the output to a file and read that file's contents

system("pgrep -P [parent_pid] 1>[outputfile]")
fp = fopen([outputfile], "r")
while (fscanf(fp, "%d", &child_pid) != EOF){
    <add child_pid to a list you've made>
}
fclose(fp)

There's definitely a better way to do this though. Look into if it's possible to call ps or pgrep from a c program.