해바

Lab #9 본문

System Programming

Lab #9

Bacha 2019. 11. 18. 02:26

fork()와 wait()를 이용하여 다음의 프로그램을 작성하라 :

  • 부모 프로세스는 두 개의 자식 프로세스를 생성한다 : Child 1, Child 2
  • 각각의 자식 프로세스는 execl()을 이용하여 "echo" 커맨드를 실행하면서 "This is Child 1(또는 Child 2)"를 출력한다.
  • 부모 프로세스는 wait() 를 실행하며 자식 프로세스들이 끝나기를 기다린다.
    wait()를 실행하기 전 "Parent: Waiting for children"하고 출력한다.
  • 자식 프로세스들이 끝나면 부모는 "Parent: All Children terminated"하고 출력한다.

 

 

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

int main() {
    int i = 0, status;
    pid_t pids[2];

    while(pids[i] = fork()) {
        if(i + 1 == 2) break;
        ++i;
    }

    switch (pids[i]) {
    case -1:
        perror("fork");
    case 0:
        switch (i) {
            case 0:
            	execl("/bin/echo", "echo", "This is Child 1", (char*) 0);
            break;
            case 1:
            	execl("/bin/echo", "echo", "This is Child 2", (char*) 0);
            break;
        }
        break;
    default:
        printf("Parent: Waiting for children\n");
        wait(&status);
        if(WIFSIGNALED(status)) printf("Sig No.: %d\n", WTERMSIG(status));
        wait(&status);
        if(WIFEXITED(status)) printf("Parent: All Children terminated\n");
        else if(WIFSIGNALED(status)) printf("Sig No.: %d\n", WTERMSIG(status));
        break;
    }

    return 0;
}

 

 

컴파일 :

%gcc wait.c

 

실행 :

%./a.out

'System Programming' 카테고리의 다른 글

Lab #11  (0) 2019.11.18
Lab #10  (0) 2019.11.18
LAB #8  (0) 2019.11.18
Lab #7  (0) 2019.11.18
Lab #6  (0) 2019.11.16
Comments