해바

LAB #8 본문

System Programming

LAB #8

Bacha 2019. 11. 18. 02:12

부모 프로세스는 sample.txt에 있는 문자열의 길이 만큼 자식 프로세스들을 생성한 후, waitpid 를 사용하여 생성된 순서대로 거두어 들이는 프로그램을 작성하라. 이 때 자식 프로세스는 자신의 순서만큼 문자열을 복사해서 output.txt에 작성하고 종료해야 한다.

 

결과 예시

sample.txt 내용

system

 

 

 

// waitpid.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <memory.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int ofd, nfd, status, len, i = 0;
    char buf[BUFSIZ];
    pid_t* pids;

    if((ofd = open("sample.txt", O_RDONLY)) == -1) perror("open");
    len = read(ofd, buf, BUFSIZ);
    pids = (pid_t*)malloc(sizeof(pid_t) * len);
    
    if((nfd = open("output.txt", O_RDWR|O_CREAT, 0644)) == -1) perror("open");

    while(pids[i] = fork()) {
        waitpid(pids[i], &status, 0);
        if(i + 1 == len) break;
        ++i;
    }

    switch (pids[i]) {
    case -1:
        perror("fork");
        break;
    case 0:
        lseek(ofd, 0, SEEK_SET);
        memset(buf, '\0', len + 1);
        read(ofd, buf, i + 1);
        printf("%s\n", buf);
        write(nfd, buf, i + 1);
        if(i + 1 != len) write(nfd, "\n", sizeof("\n"));
        break;
    default:
        break;
    }

    close(ofd);
    close(nfd);
    return 0;
}

 

 

컴파일 :

%gcc waitpid.c

 

실행 :

%./a.out

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

Lab #10  (0) 2019.11.18
Lab #9  (0) 2019.11.18
Lab #7  (0) 2019.11.18
Lab #6  (0) 2019.11.16
Lab #5  (0) 2019.11.16
Comments