2016-12-16 10 views
1

시스템 호출에 프로세스 ID가 전달되면 모든 자식 프로세스 ID를 반환해야합니다. 이것은 반드시 C로 작성해야합니다. mproc을 사용하여 자식 프로세스의 부모 프로세스를 가져오고 특정 인덱스의 모든 프로세스를 나열했지만 그로부터 도약 할 수는 없습니다.부모 프로세스의 id (minix)로부터 자식 프로세스 id를 얻는 C 프로그램

내 코드 :

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 솔루션입니다,하지만 당신은 리눅스를 실행하고 부모 프로세스의 자식을 얻으려면 당신이 사용하거나, 리눅스 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 프로그램에서 ps 또는 pgrep으로 전화하는 것이 가능한지보십시오.