C & LINUX

C / LINUX wait(2) waitpid(2)

Ocean_ 2022. 5. 2. 21:30

함수 기능

프로세스의 종료 상태를 회수하는 시스템 호출 함수

자식프로세스의 종료가 언제 발생할지 부모프로세스는 알 수 없으므로 커널은 시근ㄹ을 통해 부모 프로세스에게알림

 

wait

가장 먼저 종료된 자식 프로세스 기다림

 

waitpid

특정한 자식프로세스를 지정

함수 원형

#include <wait.h>
#include <sys/types.h>
pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);

함수 파라메터

statloc

종료될때 상태 값

 

pid

wait할 pid id

 

함수 예제

wait1

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>
#define EXIT_CODE 1 
int main(void){

    pid_t pid;
    int ret_val, status;

    /*
        프로세스를 fork하고 프로세스들의 상태를 출력
    */
    if (( pid = fork()) == 0) {
        printf ("child: pid = %d ppid = %d exit_code = %d\n", 
                getpid(), getppid(), EXIT_CODE);
        exit(EXIT_CODE);
    }

    printf ("parent: waiting for child= %d\n", pid); 
    
    /*
        프로세스 정상 종료시 exit비트는 status로 전달 된다. &연산을 통해 1이 출력된다
    */
    ret_val = wait(&status); 
    printf (" parent: return value = %d, ", ret_val); 
    printf (" child's status= %x", status); 
    printf (" and shifted= %x\n", (status>> 8)); 
    exit(0);
    }

wait2

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>

/*  
    "/bin/echo" 에 리스트형태로 exec해주는 것이다.
*/
int main(void){
    if (fork() == 0) 
        execl("/bin/echo", "echo", "this is", "message one", (char *)0); 
    
    if (fork() == 0) 
        execl("/bin/echo", "echo", "this is", "message Two", (char *)0); 

    printf ("parent: waiting for children\n");
    /*
        wait가 에러가 없을경우 parent는 죽는다.
        자식들이 출력되고 부모프로세서가 죽는다.
    */
    while (wait((int *)0) != -1);
    printf ("parent: all children terminated\n"); 
    exit(0);

}

함수 결과

wait1

wait2

 

리눅스시스템 프로그래밍 - 홍지만 저

교재 내에 있는 예제를 바탕으로 작성한 글 입니다.