C程序从父ID(minix)获取子进程ID

时间:2016-12-16 20:54:34

标签: c minix

因此,如果传递给系统调用的进程ID,我需要返回所有子进程ID。这必须用C语言编写。我使用了mproc来获取子pid的父进程,并列出了某个索引的所有进程,但是无法实现这一过程。

我的代码:

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 个答案:

答案 0 :(得分:0)

这是一个非常笨拙的解决方案,但是如果您正在运行Linux并且想要获取父进程的子进程,则可以使用pgrep {fork() {{} and execv()命令1}}或通过简单的system()电话。然后将输出传递给文件并读取该文件的内容

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)

尽管如此,肯定有更好的方法。查看是否可以从c程序中调用pspgrep

相关问题