사는(live) 이야기

[Unix C] 새로운 프로세스를 호출! fork(), exec() 정리

_파랑새 2021. 3. 9. 01:21
반응형

1. fork()

ㅇ man page

fork - man pages section 2: System Calls (oracle.com)

 

fork - man pages section 2: System Calls

fork(2) Name fork, fork1, forkall, forkx, forkallx - create a new process Synopsis #include #include pid_t fork(void); pid_t fork1(void); pid_t forkall(void); #include pid_t forkx(int flags); pid_t forkallx(int flags); Description The fork(), fork1(), fork

docs.oracle.com

ㅇ 기능

    - 새로운 프로세스를 위한 메모리가 할당된 후 현재 프로세스를 그대로 복사한다.

    - 코드, 환경변수, process group id, 파일 디스크립터 등이 그대로 복사(상속)된다.

    - 부모 프로세스는 부모 프로세스대로 코드를 진행하고 자식은 fork 된 시점부터 한줄씩 코드를 실행한다.

 

ㅇ 리턴값 

    - 자식 프로세스 : 0

    - 부모 프로세스 : 자식 프로세스의 pid

    - 리턴값이 음수이면 오류가 발생한 것이다.(리소스 수 제한, swap space 부족 등의 이유로)

 

 

2. exec()

ㅇ man page

exec - man pages section 2: System Calls (oracle.com)

 

exec - man pages section 2: System Calls

exec(2) Name exec, execl, execle, execlp, execv, execve, execvp, fexecve - execute a file Synopsis #include int execl(const char *path, const char *arg0, ... /* const char *argn, NULL */); int execv(const char *path, char *const argv[]); int execle(const c

docs.oracle.com

ㅇ 기능

    - 현재 프로세스를 새로운 이미지(프로세스)로 대체한다.

 

ㅇ 리턴값

    - 프로그램 대체가 성공적으로 완료되는 경우에는 값이 없다. 왜냐하면 호출하는 프로그램이 호출되는 프로그램으로 덮어 씌워지기 때문이다.

    - 프로그램 대체가 실패 할 경우 -1을 반환한다.

      (arguments 의 갯수가 시스템의 {ARG_MAX} 값을 넘는 경우, permission denied, memory 부족 등의 이유)

 

ㅇ 기타

    - 다른 프로그램을 호출하면서 arguments 를 넘기고 싶다면 execl()이나 execv() 를 사용하면 된다.

 

execl - man pages section 2: System Calls (oracle.com)

 

execl - man pages section 2: System Calls

execl(2) Name exec, execl, execle, execlp, execv, execve, execvp, fexecve - execute a file Synopsis #include int execl(const char *path, const char *arg0, ... /* const char *argn, NULL */); int execv(const char *path, char *const argv[]); int execle(const

docs.oracle.com

execv - man pages section 2: System Calls (oracle.com)

 

execv - man pages section 2: System Calls

execv(2) Name exec, execl, execle, execlp, execv, execve, execvp, fexecve - execute a file Synopsis #include int execl(const char *path, const char *arg0, ... /* const char *argn, NULL */); int execv(const char *path, char *const argv[]); int execle(const

docs.oracle.com

 

 

그래서

 

한 프로그램에서 다른 프로그램을 호출한 후 다음 코드를 실행하고 싶다면 fork() 와 exec() 를 함께 사용해야한다.

호출한 프로그램의 반환값은 signal() 함수로 받아 nonblock, sync 방식의 코딩이 가능하다.

 

 

fork-exec 예제코드(출처 참고)

출처 : [유닉스] fork와 exec – 검은색 잉크 블로그 (blackinkgj.github.io)

 

반응형