#include <stdio.h>
#include <stdlib.h>
void sign_off(void);
void too_bad(void);
int main(void)
{
int n;
atexit(sign_off);
puts("Enter an integer:");
if(scanf("%d",&n) != 1)
{
puts("That's no integer!");
atexit(too_bad);
exit(EXIT_FAILURE);
}
printf("%d is %s.\n", n, (n % 2 == 0) ? "even" : "odd");
return 0;
}
void sign_off(void)
{
puts("Thus terminates another magnificent program from");
puts("SeeSaw Software!");
}
void too_bad(void)
{
puts("SeeSaw Sftware extends its heartfelt condolences");
puts("to you upon the failure of your program.");
}
#include <stdlib.h>
void sign_off(void);
void too_bad(void);
int main(void)
{
int n;
atexit(sign_off);
puts("Enter an integer:");
if(scanf("%d",&n) != 1)
{
puts("That's no integer!");
atexit(too_bad);
exit(EXIT_FAILURE);
}
printf("%d is %s.\n", n, (n % 2 == 0) ? "even" : "odd");
return 0;
}
void sign_off(void)
{
puts("Thus terminates another magnificent program from");
puts("SeeSaw Software!");
}
void too_bad(void)
{
puts("SeeSaw Sftware extends its heartfelt condolences");
puts("to you upon the failure of your program.");
}
결과
Enter an integer:
1 // 숫자 입력시
1 is odd.
Thus terminates another magnificent program from
SeeSaw Software!
Press ENTER or type command to continue
Enter an integer:
q // 문자 입력시
That's no integer!
SeeSaw Sftware extends its heartfelt condolences
to you upon the failure of your program.
Thus terminates another magnificent program from
SeeSaw Software!
Enter an integer:
1 // 숫자 입력시
1 is odd.
Thus terminates another magnificent program from
SeeSaw Software!
Press ENTER or type command to continue
Enter an integer:
q // 문자 입력시
That's no integer!
SeeSaw Sftware extends its heartfelt condolences
to you upon the failure of your program.
Thus terminates another magnificent program from
SeeSaw Software!
- atexit
: 이 함수는 exit()가 호출될때 실행되는 함수 리스트에 해당 함수를 등록한다. atexit()에 등록되는건 함수 포인터 형식이다. 함수명 자체가 주소값이므로 그냥 함수명을 인수로 사용하면 된다. ANSI에서는 32개까지의 등록을 보장한다. 스택처럼 맨처음 추가된 함수가 맨 나중에 호출이 된다. FILO(First In Last Out). 보통 프로그램 모니터링 파일을 업데이트 하거나 환경 변수를 재설정하는 등의 업무를 실행한다. exit()는 별도로 호출하지 않더라도 프로그램이 종료될때 exit()함수를 무조건 호출하므로 위와 같은경우 적어도 sign_off함수는 반드시 출력된다. 이 함수는 exit()가 호출된 후 실행된다.
- exit()
: atexit()로 지정된 함수는 exit() 이후에 실행한 후 스스로 정리한다. exit()는 모든 출력 스트림을 플러쉬(flush)하고, 개방된 모든 스트림을 닫고, 표준 I/O함수 tmpfine()의 호출로 만들어진 임시 파일을 닫는다. 그런 다음 exit()는 호스트 환경으로 제어를 반환하고, 가능하면 그 환경에 종료 상황을 보고한다. 전통적으로 UNIX프로그램은 성공적인 종료를 표시하는데 0을 사용하고 실패를 표시하는데 0이아닌 수를 사용하고 있다. exit()함수는 return문을 사용하는 것과 동일하다. 다른점은 exit()는 mail()함수외의 다른 함수에서 사용되면 종료가 된다. return은 값을 반환하겠지만 말이다..
댓글 없음:
댓글 쓰기