Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 전자책
- LJESNJAK
- system programming
- For Beginners
- 4949
- 입력 버퍼
- 시스템 프로그래밍
- c
- 백준
- 해바
- 1874
- IT
- 브런치
- process control
- file IO
- QA
- The Balance of the World
- Zero That Out
- Baekjoon
- 바샤
- Process Communication
- 시프
- 10773
- c++
- BAKA
- 균형잡힌 세상
- Parenthesis
- 5622
- File 조작
- 2941
Archives
- Today
- Total
해바
LAB #8 본문
부모 프로세스는 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
Comments