Software/Embedded system

fork() system call concept

neovaga 2021. 6. 27. 15:21
반응형

 fork() : Create new process, Clone current process // system call

 ->Have exactly the same stack (sequence of function calls)

 ->Have same virtual memory ( so pointer and other data is preserved)

 ->No argument

 ->Return process Id of the child process

-> After creation of the process both parent and child process starts execution from next the instruction

 

fork() > 0 //Successful 

fork() < 0 // Error

fork() == 0 // Child process 

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main ()
{

printf("Start:PID:%d\n", getpid());
int pid_child_1 = fork();
int pid_child_2 = fork();
printf("child_1 :PID:%d\n", pid_child_1);
printf("child_2 :PID:%d\n", pid_child_2);
printf("how many times print: Current PID:%d\n", getpid());
}
OutPut:
Start:PID:4032
child_1 :PID:4033
child_2 :PID:4034
how many times print: Current PID:4032
child_1 :PID:4033
child_2 :PID:0
how many times print: Current PID:4034
child_1 :PID:0
child_2 :PID:4035
how many times print: Current PID:4033
child_1 :PID:0                                                                                      
child_2 :PID:0
how many times print: Current PID:4035

간단히 코드를 정리하면 아래와 같이 동작이 하게 된다. fork를 실행하게 되면 그 다음 실행문부터 호출되게 된다. 그리고 해당 fork의 리턴값으로 자식프로세스인지 아닌지 확인이 가능하다. 

어떤 fork가 먼저 실행이 되서 print가 될지는 다중 프로세스이기 때문에 시스템에 따라서 실행순서가 다를수 있다. 

각 프로세스는 하나의 부모프로세스를 가질수 있다. getppid()로 부모프로세스 ID확인이 가능하다. 자식프로세스는 parent's data space, heap and stack를 복사하고 서로 이값을을 공유하지는 않는다. 

 위 예제처럼 fork를 사용해서 부모프로세스 ID를 확인하면 1 로 값이 return 이 된다. 이유는 자식 프로세스가 getppid()를 호출했을때 이미 부모프로세스가 종료가 되어 버리면 자식프로세스가 1로 초기화 값을 할당하게 된다. 이럴때 부모프로세스 값을 확인 하려면 부모프로세스가 끝나지 않게 sleep()을 주거나 delay()를 넣어주면 해당 값 확인이 가능하다.

 

Forking processes has advantages:

1. Fault Tolerance (고장방지능력): 자식 프로세스에서 문제가 발생해도 부모 프로세스에는 큰 사용성의 문제가 없게 복구 개선 할수 있다. 

2. Serurity (보안): 부모와 자식에 다른 보안 셋팅을 할 수 있다. 

3. Low latency(저지연, 빠른 대기): 메모리와 I/O 스트림의 시작을 최소화 한다. 

4. Concurrency & Performance (동시성, 성능): 부모와 자식프로세스가 함께 다른 동작으로 실행하기에 성능이 향상된다. 

5. Resouce utilization (자원활용): 프로세스들이 효과적으로 전체 자원을 사용가능 하다.

6. Monitoring & debugging (모니터, 디버깅): 독립적인 프로세스들이기에 쉽게 확인, 디버깅 하고 종료 할 수 있다. 

반응형

'Software > Embedded system' 카테고리의 다른 글

C 프로그램 빌드 과정 정리  (0) 2021.08.09
exec() System call concept  (0) 2021.06.27
Memory - stack and heap  (0) 2021.05.26
Priority Inversion (feat. Embeded system)  (0) 2021.05.23
Threads Concept  (0) 2021.05.23