2016-12-16 112 views
1

因此,給定一個傳遞給系統調用的進程ID,我需要返回所有子進程id。這必須用C語言編寫。我使用mproc來獲取子進程的父進程,並列出來自某個索引的所有進程,但是無法從此跳到這一步。C程序從父母id(minix)獲取子進程ID

我的代碼:

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; 
} 
+0

不要評論你希望我們幫助的代碼,語法高亮顯示使得它很難閱讀。 – Barmar

+0

@Barmar道歉 - 編輯。 – Jimmy

回答

0

這是一個非常janky的解決方案,但如果你運行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