Development/Linux

[Linux] 시스템 호출 관련 프로세스 관리 - fork, exec, wait, getpid 등

oneonlee 2022. 4. 17. 20:53
반응형

Process related system calls

1. process

A program loaded in the memory.

process = body + process descriptor

body = code + data + stack

  • ps -ef 명령어는 현재 메모리에 로드된 모든 프로세스를 보여준다.
  • ps -f 명령어는 현재 터미널에서 실행 중인 프로세스를 나타낸다.
  • 시스템은 round-robin 방식으로 각 프로세스를 하나씩 실행한다.
    • 스케줄러는 실행할 다음 프로세스를 선택하고 CPU는 이를 짧은 시간(예: 프로세스당 10ms, time quantum이라고 부름) 동안 실행하고 스케줄러는 다음 실행할 프로세스를 선택한다.

2. System calls to manage processes

  • fork: 프로세스를 복제
  • exec: 프로세스를 다른 프로세스로 변환
  • exit: 프로세스 중지
  • wait: 자식 프로세스(child process)가 종료될 때까지 대기
  • getpid: process ID를 get
  • getppid: parent process ID를 get

What happens when a program calls fork():

  • copy body
    • copy process descriptor
    • adjust child's process descriptor
    • return 0 to child
    • return child's pid to parent
    • scheduler picks the parent or the child
    • the selected process starts to run AFTER fork()

3. Example

아래 코드("ex5.c")를 실행했을 때, "hello" 가 얼마나 나타날까?

"ex5.c"

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

int main(){
   int x,y;
   x=fork();
   y=fork();
   printf("hello: %d %d\n", x, y);
}
$ gcc –o ex5 ex5.c
$ ex5
hello: 41139 41140
hello: 41139 0
hello: 0 41141
hello: 0 0
  • "ex5"를 실행하면 4개의 "hello"가 출력되는 것을 확인할 수 있다.
  • fork()를 한 번하면 총 2개에 프로세스가 생성된다.
  • 연속적으로 fork()를 두 번 하게 되면, 처음에 생긴 프로세스 각각 fork()를 수행하게 되므로 "4 (= 2^2)"개의 프로세스가 생성된다.
  • 첫 번째 출력은 x, y 모두 0이 아니기 때문에 최초의 부모 프로세스로부터 생성된 것이다.
  • 두 번째와 세 번째 출력은 x0이기 때문에 첫 번째 fork()로 복사된 프로세스에서 생성된 것으로, 두 번째 출력은 1번만 복사된 것, 세 번째는 2번 복사된 프로세스이다.
  • 마지막 출력은 부모 프로세스로부터 두 번째 fork()에서 복사된 프로세스에서 출력된 것을 x0이 아니지만 y0임에서 알 수 있다.

이를 Process Tree로 그리면 아래와 같다.

 


 

추가적인 예제 및 실습 문제들을 확인하고 싶으시면 아래 링크를 클릭해주세요 :)

 

GitHub - oneonlee/Computer-Science: Introduction to Computer Science

Introduction to Computer Science. Contribute to oneonlee/Computer-Science development by creating an account on GitHub.

github.com

 

반응형