운영체제 6주차
부산가톨릭 대학교, 컴퓨터공학과
변상선
Process concept
•
프로세스•
사용자로부터 실행 요청을 받은 프로그램•
A program in execution•
하나의 프로그램이 여러 프로세스로 구성 될 수 있음•
프로세스 구성 요소•
Program code•
PCB (process control block)•
Program counter, registers, etc.•
Stack•
Heap•
Data section => global variableProcess in memory
Process state
•
New•
프로세스가 생성되고 있는 상태•
Running•
프로세서에 의해 현재 실행중인 상태•
Waiting•
프로세스가 다른 어떤 상태가 발생하기를 기다리고 있는 상태•
Ready•
프로세서에 의해 실행 될 수 있는 상태•
Terminated•
실행이 종료된 상태•
Zombie (또는 defunct)•
리눅스: 자식 프로세스는 종료가 되었으나, 부모 프로세스가 wait() 시스템 콜을 통해 자식 프로세 스의 종료를 리턴 받지 않은 경우, 종료는 되었으나 계속해서 운영체제의 프로세스로 관리Process state transition
PCB
•
Process table, task control block•
Process state - running, waiting, etc.•
Program counter•
CPU registers - 이 프로세스가 사용하는 레지스 터의 현재 값들•
Scheduling 정보 - 우선순위•
Memory 정보 - 프로세스에게 할당된 메모리 정보•
Accouting information - CPU 사용시간, 실행 시 간•
I/O status - 사용중인 (이 프로세스에 의해 open 된) 입출력 장치, 파일CPU switch from process to process
인터럽트 또는 시스템 콜 수행
Threads
• 하나의 최소 실행단위
• 하나의 프로세스 내에서 문맥의 전환없이 실행되는 최소단위
• Single-threaded vs. multi-threaded
Process scheduling
•
스케쥴링 정책에 의해 다음에 실행되어질 프로세스를 선택•
Long-term scheduling & short-term scheduling•
현재 실행중인 프로세스를 필요시 선점 (preemption)•
프로세스들의 큐를 관리•
Job queue - 시스템에 있는 모든 프로세스•
Ready queue (run queue) - 실행 가능한 모든 프로세스•
Wait queue (device queue) - I/O나 어떤 이벤트를 기다리는 프로세스•
프로세스의 상태에 따라서 큐와 큐를 오감Ready queue and various
I/O device queues
Representation of process scheduling
Wait queue에서 대기 선점되는 경우 곧바로 ready queue로 이동
Scheduler
•
Long-term scheduler (or job scheduler)•
Ready queue로 추가할 프로세스 선택•
Short-term scheduler (or CPU scheduler)•
CPU를 사용할 프로세스를 ready queue에서 선택•
따라서, STS가 훨씬 빈번하게 수행•
I/O bound process, CPU-bound process•
LTS 의 역할이 두 종류의 프로세스들을 적당히 섞어서 ready queue에 삽입•
컴퓨터 시스템 전반 (CPU와 I/O)의 성능을 극대화Context switch
• CPU가 현재 실행중인 프로세스의 실행을 중단하 고 다른 프로세스를 실행하는 것
• 다른 프로세스로 실행을 넘어가기전에 직전에 수 행했던 프로세스의 상태를 PCB에 저장
• Context switch는 overhead
• 너무 잦은 switch는 자제
• 모드 전환, 캐쉬 플러쉬, 페이지 테이블 전환 등
Process creation
•
일반적으로 부모 프로세스가 자식 프로세스를 생성 => fork•
예) 리눅스의 ‘init’ 프로세스 =>리눅스가 부팅되면 생성되는 최초의 프로세스 => 다른 모 든 프로세스는 이 프로세스로부터 fork•
생성되면 pid를 부여•
자원 공유•
부모 프로세스의 모든 자원을•
완전히 공유•
일부만 공유•
전혀 공유 X•
실행•
부모프로세스와 병렬적 (concurrently)으로 실행•
자식프로세스가 종료될 때까지 부모는 수행을 멈추고 기다림 (wait)Process tree in Linux
init pid = 1
sshd pid = 3028 login
pid = 8415 kthreadd
pid = 2
sshd pid = 3610 pdflush
pid = 200 khelper
pid = 6
tcsch pid = 4005 emacs
pid = 9204 bash
pid = 8416
ps pid = 9298
Process creation
•
주소 공간•
UNIX 시스템•
fork ()•
새로운 주소공간과 프로세스 테이블 생성•
부모 프로세스가 자식 프로세스로 그대로 복사되어 동시에 실행•
exec(“프로세스 이름”)•
부모 프로세스의 주소공간에서 “프로세스 이름”으로 명시된 프로세스가 실행•
fork() => exec(“프로세스 이름”)•
새로운 주소공간에서 “프로세스 이름”으로 명시된 프로세스가 실행Process creation
•
fork() 시스템 콜•
#include <unistd.h>#include <stdio.h>
int main() { pid_t pid;
pid = fork();
if (pid > 0)
printf (“I am the parent of pid=%d!\n”, pid);
else if (!pid)
printf(“I am the child!\n”);
else if (pid == -1) printf(“Error\n”);
}
Process creation
• fork() => exec family
•#include <unistd.h>
#include <stdio.h>
int main() { pid_t pid;
pid = fork();
if (pid == -1) printf(“Error\n”);
if (!pid) {
const char *args[] = {“vi”, NULL};
int ret;
ret = execvp (“vi”, args);
if (ret == -1) { printf(“Error\n”);
exit (EXIT_FAILURE);
} } }
Process termination
•
exit () 시스템 콜•
부모 프로세스의 wait() 시스템 콜로 전달•
자식 프로세스가 종료되는것을 기다리는 시스템 콜•
부모 프로세스가 wait() 시스템 콜을 호출하지 않은 상태 에서 자식 프로세스가 종료되면 자식 프로세스의 상태는 zombile state•
프로세스가 사용했던 자원이 OS에 의해 해제됨•
abort() 시스템 콜•
부모 프로세스가 자식 프로세스를 강제로 종료Wait () 시스템 콜
•
#include <unistd.h>#include <string.h>
#include <stdio.h>
int main() { int pid;
pid = fork();
if (pid == 0) { sleep(5) exit(1);
} else if (pid > 0) { getchar();
} }
•
Zombie process 확인•
ps -ef | grep defunct | grep -v grep•
ps -ef | grep defunct | awk ‘{print $3}’ | xargs kill -9Wait () 시스템 콜
•
#include <unistd.h>#include <string.h>
#include <stdio.h>
int main() { int pid;
int status;
pid = fork();
if (pid == 0) { sleep(5) exit(1);
} else if (pid > 0) { getchar();
pid = wait(&status);
} }
•
Zombie process 종료 확인Interprocess
communication (IPC)
•
Cooperating processes•
특정 목적을 위해 다수의 프로세스가 협조•
Information sharing, computation speed up, and synchronization•
Shared memory & message passingprocess A
message queue
kernel
(a) (b)
process A shared memory
kernel process B
m0 m1 m2 m3 ... mn
process B
IPC
• Shared memory
• 프로세스의 메모리 공간을 다른 프로세스와 공유
• 프로세스의 메모리 공간을 커널 영역으로 맵핑하여 다른 프로세스와 공유
• 사용자 프로세스에 의한 공유공간 관리
• Producer-consumer problem
• Message passing
• 커널 내부의 메시지 큐를 이용하여 IPC
• 커널에 의한 공유 공간 관리
• Pipe, Unix Domain Socket, Message Queue, Mail Box, Mail Slot
IPC - pipe
• #include <unistd.h>
int pipe (int filedes[2]);
• One pipe for reading and the other for writing => half-duplex
* Named pipe (stream pipe) => full-duplex
parent child
fork
pipe user
kernel
fd[0] fd[1] fd[0] fd[1]
IPC - pipe
•
#include <unistd.h>#include <stdlib.h>
#include <stdio.h>
int main() { int n, fd[2];
pid_t pid;
char line[100];
if (pipe(fd) < 0) {
perror(“pipe error : “);
exit(0);
}
if ((pid = fork()) < 0) { perror(“fork error:”);
exit(0);
}
•
else if (pid > 0) { close(fd[0]);write(fd[1], “hello world\n”, 12);
} else {
close(fd[1]);
n = read(fd[0], line, 100);
printf(“Received from parent %s\n”, line);
}
exit(0);
}