Do You Coding?
[function] exit ํจ์ ์์๋ณด๊ธฐ ๋ณธ๋ฌธ

๐ ๋งค๋ด์ผ (Linux)
NAME
exit() - End Program
: ํ๋ก๊ทธ๋จ ์ข ๋ฃํ๊ธฐ
SYNOPSIS
#include <stdlib.h>
void exit(int status);
DESCRIPTION
The exit() function returns control to the host environment from the program. It first calls all functions that are
registered with the atexit() function, in reverse order; that is, the last one that is registered is the first one
called. It deletes all buffers and closes all open files before ending the program.
The argument status can have a value from 0 to 255 inclusive, or be one of
the macros EXIT_SUCCESS or EXIT_FAILURE. A status value of EXIT_SUCCESS
or 0 indicates a normal exit;
otherwise, another status value is returned.
: exit() ํจ์๋ ํ๋ก๊ทธ๋จ์์ ํธ์คํธ ํ๊ฒฝ์ผ๋ก ์ ์ด๊ถ์ ๋ฐํํฉ๋๋ค. ๋จผ์ atexit() ํจ์์ ๋ฑ๋ก๋ ๋ชจ๋ ํจ์๋ฅผ
์ญ์์ผ๋ก ํธ์ถํฉ๋๋ค. ์ฆ, ๋ง์ง๋ง์ผ๋ก ๋ฑ๋ก๋ ํจ์๋ฅผ ์ฒซ ๋ฒ์งธ ํจ์๋ก ํธ์ถํฉ๋๋ค. ํ๋ก๊ทธ๋จ์ ์ข ๋ฃํ๊ธฐ ์ ์
๋ชจ๋ ๋ฒํผ๋ฅผ ์ญ์ ํ๊ณ ์ด๋ฆฐ ํ์ผ์ ๋ชจ๋ ๋ซ์ต๋๋ค.
์ธ์ ์ํ๋ 0์์ 255 ์ฌ์ด์ ๊ฐ์ ํฌํจํ๊ฑฐ๋ ๋งคํฌ๋ก EXIT_SUCCESS ๋๋ EXIT_FAILUE ์ค
ํ๋์ผ ์ ์์ต๋๋ค. EXIT_SUCCESS ๋๋ 0์ ์ํ ๊ฐ์ ์ ์์ ์ธ ์ข
๋ฃ๋ฅผ ๋ํ๋
๋๋ค;
๊ทธ๋ ์ง ์์ผ๋ฉด ๋ค๋ฅธ ์ํ ๊ฐ์ด ๋ฐํ๋ฉ๋๋ค.
RETURN VALUE
The exit() function returns both control and the value of status to the operating system.
: exit() ํจ์๋ ์ปจํธ๋กค๊ณผ ์ํ ๊ฐ์ ๋ชจ๋ ์ด์ ์ฒด์ ์ ๋ฐํํฉ๋๋ค.
๐ ํจ์ ์ค๋ช
exit ํจ์๋ atexit()ํจ์๋ก ๋ฑ๋ก๋ ์ข ๋ฃ ํธ๋ค๋ฌ๋ฅผ ์ฒ๋ฆฌํ๊ณ ํ์ค ์ ์ถ๋ ฅ ์คํธ๋ฆผ์ ๋ซ์ ํ, ์ปค๋์ ์ข ๋ฃ ์์ ์ ์คํํ๋ค.
๋จ์ํ๊ฒ ๋งํ์๋ฉด, ์ค์ ํด๋ ๊ณผ์ ์ ๊ฑฐ์น๋ฉฐ ์ข ๋ฃ๋ฅผ ์์ผ์ฃผ๋ ํจ์์ด๋ค.
ํน์ง์ ์ธ ๋ถ๋ถ์ผ๋ก๋, ๋ชจ๋ ์ด๋ ค์ง ํ์ผ์ ์๋์ผ๋ก ๋ซ์ผ๋ฉฐ, ์ถ๋ ฅ ๋ฒํผ ์ ๋ฐ์ดํฐ๊ฐ ์์ผ๋ฉด ์ฐ๊ธฐ ์๋ฃ ์ํจ๋ค.
์ ๋ ฅ ์ธ์์ธ status๋ ์ด์์ฒด์ ๋ก ์ ๋ฌ๋๋ฉฐ return์ ์ ๋ฌ๊ฐ๊ณผ ๊ฐ์ ์ญํ ์ด ๋๋ค.
๊ทธ๋ ๋ค๋ฉด, exit ํจ์์ ์ธ์์ธ status๋ ์ด๋ค๊ฑธ๊น?
stdlib.h์ ํด๋น status ์์๊ฐ ์ ์๋์ด ์๋ค.
| ์ ์๋ ์์๋ช | ๊ฐ |
| EXIT_SUCCESS | 0 |
| EXIT_FAILURE | 1 |
์์ ๊ฐ์ด, status์ ๊ฐ์ด 0์ด ๋ค์ด๊ฐ๋ฉด, ์ ์์ ์ผ๋ก ์ข ๋ฃ๋ ์ํฉ์ผ๋ก ๊ฐ์ฃผํ๊ณ ,
0์ด ์๋ ์ซ์(๋์ฒด์ ์ผ๋ก 1์ ๋ฐํํ๊ณ , ์ด์ธ์ ์ซ์๋ ๋์ ๊ฐ๋ฅ) ๊ฐ ๋ค์ด๊ฐ๊ฒ ๋๋ฉด ์ด๋ค ์ค๋ฅ์ ์ํด ์ข ๋ฃ๋ ์ํฉ์ผ๋ก ๋ณธ๋ค.
main๋ฌธ์์์ return(0); ์ exit(0)์ ๋์ผํ์ง๋ง,
exit์ ์ด์์ฒด์ ์๊ฒ ๊ถํ์ ์ฃผ๋ฉฐ ๋ฐ๋ก ํ๋ก์ธ์ค๋ฅผ ์ข ๋ฃํ๊ณ , return์ ๋ค ๋ฌธ์ฅ์ ์คํํ๋ฉฐ ํ๋ก๊ทธ๋จ ์ ์ฒด๋ฅผ ์ค์ง์ํจ๋ค.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
printf("์์ ์ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.");
scanf("%d", &i);
if(i <= 0)
exit(1);
exit(0);
}
์ ๋ ฅ ๋ฐ ๊ฒฐ๊ณผ - fish shell)

์ผ๋ฐ shell์์ ํ์ธํ๋ฉด ๋๊ฐ์ด ์ข ๋ฃ๋ ๊ฒ๋ง ์ ์ ์๊ณ ,
fish shell ์์ ํ์ธํ๋ฉด exit(1)์ด ์คํ๋ ๊ฒ์ [1]๋ก ํ์ธํ ์ ์๋ค.
๋ง์ฝ exit(1)์๋ฆฌ์ exit(5)๊ฐ ๋ค์ด๊ฐ๋ฉด, [1]์ด [5]๋ก ๋ฐ๋๊ณ ,
์ง์ ํ status๋ฅผ ์ด์์ฒด์ ๋ก ์ ๋ฌํ ๋ชจ์ต์ ๋ณผ ์ ์๋ค.
ํด๋น exit(1)์๋ฆฌ๊ฐ return(1)์ผ๋ก ๋ฐ๋์ด๋ ๋์ผํ๋ค.
'CS & Engineering > C' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [function] pipe ํจ์ ์์๋ณด๊ธฐ (0) | 2024.06.06 |
|---|---|
| [function] fork ํจ์ ์์๋ณด๊ธฐ (2) | 2024.06.04 |
| [function] execve ํจ์ ์์๋ณด๊ธฐ (0) | 2024.05.30 |
| [function] dup2 ํจ์ ์์๋ณด๊ธฐ (2) | 2024.05.28 |
| [function] dup ํจ์ ์์๋ณด๊ธฐ (0) | 2024.05.27 |
