【问题标题】:C program to get child process id's from just a parent id (minix) [duplicate]C程序仅从父ID(minix)获取子进程ID [重复]
【发布时间】:2016-12-16 20:54:34
【问题描述】:

所以给定一个传递给系统调用的进程 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;
}

【问题讨论】:

  • 不要注释掉需要我们帮助的代码,语法高亮会让人难以阅读。
  • @Barmar 道歉 - 已编辑。

标签: c minix


【解决方案1】:

这是一个非常笨拙的解决方案,但是如果您正在运行 linux 并且想要获取父进程的子进程,则可以使用 linux pgrep 命令,通过使用 fork() and execv() 或通过简单的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

【讨论】:

    猜你喜欢
    • 2017-05-23
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2012-12-27
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多