시작하기
Hello World
모든 C 프로그램은 main()에서 시작합니다. #include <stdio.h>는 표준 I/O 라이브러리(printf, scanf)를 가져옵니다. main은 성공 시 0, 실패 시 0이 아닌 값을 반환합니다. void 키워드는 main이 매개변수를 받지 않음을 명시적으로 선언합니다.
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}변수 & 타입
C는 정적으로 타입이 지정됩니다. 일반 타입: int, float, double, char. float는 f 접미사가 필요합니다. char[]은 문자열(널 종료 배열)입니다. long과 short는 크기 한정자입니다. unsigned는 음이 아닌을 의미합니다. 크기는 플랫폼에 따라 다름; 고정 너비를 위해 <stdint.h>를 사용하세요.
int age = 30;
float height = 5.7f;
double pi = 3.14159;
char grade = 'A';
char name[] = "Alice";
long big = 100000L;
unsigned int count = 42;
printf("%s is %d\n", name, age);입력 & 출력
scanf는 입력을 저장할 변수의 주소(&)가 필요합니다. 버퍼 오버플로우를 방지하기 위해 항상 문자열 입력 길이를 제한하세요(50자 버퍼의 경우 %49s). scanf는 공백에서 문자열 읽기를 중지; 전체 줄은 fgets를 사용하세요.
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("You entered %d\n", n);
char name[50];
printf("Enter name: ");
scanf("%49s", name); // limit to prevent overflow
printf("Hi, %s!\n", name);printf 형식 지정자
형식 지정자는 출력을 제어: %d 정수, %f 실수, %c 문자, %s 문자열, %x 16진수, %p 포인터. 너비와 정밀도(예: %5.2f)는 정렬과 소수를 제어합니다. 지정자와 타입이 일치하지 않으면 정의되지 않은 동작을 유발합니다.
printf("%d\n", 42); // integer
printf("%f\n", 3.14); // float/double
printf("%.2f\n", 3.14159); // 3.14 (2 decimals)
printf("%c\n", 'A'); // char
printf("%s\n", "hello"); // string
printf("%x\n", 255); // ff (hex)
printf("%5d\n", 42); // right-aligned, width 5
printf("%-5d|\n", 42); // left-aligned전처리기 & 헤더
전처리기는 컴파일 전에 실행됩니다. #include는 헤더 파일을 붙여넣고, #define은 매크로와 상수를 생성합니다. 이중 포함을 방지하기 위해 헤더에 항상 include guard(#ifndef/#define/#endif)를 사용하세요. 매크로는 텍스트 치환 — 매개변수 주변에 괄호를 사용하세요.
#include <stdio.h> // system header
#include "myheader.h" // local header
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
#ifndef GUARD_H
#define GUARD_H
// header content
#endif문자열 & String.h
문자열 기본
C 문자열은 널 종료 char 배열입니다. strlen은 '\0' 전의 문자를 셈; sizeof는 버퍼 크기를 반환합니다. strcpy는 널 종료자까지 복사 — 오버플로우를 피하기 위해 항상 대상이 충분히 큰지 확인하세요.
#include <string.h>
char s[20] = "Hello";
printf("Length: %zu\n", strlen(s)); // 5
printf("Size: %zu\n", sizeof(s)); // 20
char dest[20];
strcpy(dest, s); // copy
printf("%s\n", dest); // Hello연결 & 비교
strcat은 추가(대상에 공간이 있어야 함). strcmp는 사전순으로 비교: 같으면 0, 첫 번째 < 두 번째면 음수, 첫 번째 > 두 번째면 양수. 문자열 비교에 ==를 절대 사용하지 마세요(내용이 아닌 포인터 비교).
#include <string.h>
char s[30] = "Hello";
strcat(s, ", World!"); // s = "Hello, World!"
printf("%s\n", s);
int cmp = strcmp("apple", "banana");
// returns <0 if a<b, 0 if equal, >0 if a>b
if (strcmp(s, "Hello") == 0) {
printf("Equal!\n");
}sprintf & sscanf
sprintf는 문자열 버퍼에 형식화(printf와 같지만 문자열로). sscanf는 문자열을 변수로 파싱(scanf와 같지만 문자열에서). 최대 크기를 지정하여 버퍼 오버플로우를 방지하기 위해 sprintf 대신 snprintf를 사용하세요.
char buf[100];
int age = 30;
char name[] = "Alice";
sprintf(buf, "%s is %d years old", name, age);
printf("%s\n", buf);
int a, b;
sscanf("10 20", "%d %d", &a, &b);
printf("a=%d, b=%d\n", a, b); // a=10, b=20strchr, strstr & strtok
strchr은 문자를 찾고, strstr은 부분 문자열을 찾습니다. strtok은 구분자로 문자열을 분할하지만 원본 문자열을 수정(널 종료자 삽입)하고 스레드 안전하지 않음 — 토큰화를 계속하려면 후속 호출에서 NULL을 전달하세요.
#include <string.h>
char s[] = "Hello, World!";
char *p = strchr(s, 'W'); // find first 'W'
printf("%s\n", p); // World!
char *sub = strstr(s, "World");
printf("%s\n", sub); // World!
char tokens[] = "a,b,c";
char *tok = strtok(tokens, ",");
while (tok) {
printf("%s\n", tok);
tok = strtok(NULL, ",");
}fgets & 안전한 입력
fgets는 안전한 문자열 읽기 방법 — 오버플로우를 방지하기 위해 크기 제한을 받습니다. scanf와 달리 공백을 읽습니다. 줄바꿈이 결과에 포함됨; strcspn으로 찾아 제거하세요. gets(C11에서 제거됨)보다 항상 fgets를 선호하세요.
char line[100];
printf("Enter text: ");
fgets(line, sizeof(line), stdin);
// removes trailing newline
line[strcspn(line, "\n")] = 0;
printf("You said: %s\n", line);숫자 & 수학
정수 타입 & 제한
정확한 크기가 중요할 때 고정 너비 타입(int32_t, int64_t)을 위해 <stdint.h>를 사용하세요. <limits.h>는 플랫폼별 경계를 위해 INT_MAX, INT_MIN 등을 제공합니다. LL 접미사는 long long 리터럴을 표시합니다. int/long의 크기는 플랫폼에 따라 다릅니다.
#include <stdint.h>
#include <limits.h>
int32_t a = 100;
int64_t big = 9223372036854775807LL;
uint8_t byte = 255;
printf("INT_MAX = %d\n", INT_MAX); // 2147483647
printf("INT_MIN = %d\n", INT_MIN); // -2147483648
printf("UINT_MAX = %u\n", UINT_MAX); // 4294967295부동 소수점
float는 4바이트(6-7자리 정밀도), double은 8바이트(15-16자리). 반올림 오류로 인해 float를 ==로 비교하지 마세요 — fabs(a - b) < epsilon 사용. <float.h>는 경계와 정밀도를 위해 DBL_MAX, DBL_EPSILON을 제공합니다.
#include <float.h>
double d = 3.141592653589793;
float f = 3.14f;
printf("DBL_MAX = %e\n", DBL_MAX);
printf("DBL_EPSILON = %e\n", DBL_EPSILON);
if (d == 0.1 + 0.2) {
// likely false! floating point imprecision
}수학 함수
<math.h>는 표준 수학 함수를 제공합니다. pow와 sqrt는 double을 반환합 니다. fabs는 abs의 실수 버전(abs는 int용). 일부 시스템에서는 -lm으로 링크하세요. 재무 계산의 경우 부동 소수점을 피하고 정수 센트를 사용하세요.
#include <math.h>
double x = 2.5;
pow(x, 3); // 15.625
sqrt(x); // 1.581
fabs(-5.0); // 5.0
floor(3.7); // 3.0
ceil(3.2); // 4.0
fmod(10.5, 3); // 1.5
exp(1); // 2.718 (e^1)
log(2.718); // 1.0 (natural log)난수
rand()는 0에서 RAND_MAX까지의 의사 난수 int를 반환합니다. 프로그램 시작 시 srand()로 한 번 시드(time(NULL) 사용). rand() % N은 모듈로 편향과 낮은 품질; 심각한 사용의 경우 /dev/urandom을 읽거나 제3자 PRNG 라이브러리를 사용하세요.
#include <stdlib.h>
#include <time.h>
srand(time(NULL)); // seed once at start
int r = rand() % 100; // 0-99
int dice = rand() % 6 + 1; // 1-6
float fr = (float)rand() / RAND_MAX; // 0.0 - 1.0타입 변환 & 캐스팅
캐스팅은 (type)value입니다. 정수 나눗셈은 잘림 — 실수 결과를 얻으려면 실수 피연산자를 사용하세요. atoi/atof는 문자열을 숫자로 변환하지만 에러 검사 없음; errno로 파싱 에러를 보고하는 strtol/strtod를 선호하세요.
int i = 65;
char c = (char)i; // 'A'
double d = 3.99;
int truncated = (int)d; // 3
// Implicit promotion
int a = 5;
double result = a / 2.0; // 2.5 (promoted to double)
int bad = a / 2; // 2 (integer division)
// String to number
int n = atoi("42");
double f = atof("3.14");제어 흐름
If / Else
if/else if/else는 표준 조건문입니다. C는 0을 false, 0이 아닌 모든 값을 true로 취급합니다. 나중에 줄을 추가할 때 버그를 방지하기 위해 단일 명령문에도 중괄호를 사용하세요. C89에는 boolean 타입이 없음; C99는 _Bool과 <stdbool.h>를 추가합니다.
int score = 85;
if (score >= 90) {
printf("A\n");
} else if (score >= 80) {
printf("B\n");
} else if (score >= 70) {
printf("C\n");
} else {
printf("F\n");
}Switch
switch는 일치하는 case 레이블로 점프합니다. fall-through를 방지하기 위해 항상 break를 사용(케이스 6과 7은 의도적으로 코드 공유). default는 일치하지 않는 값을 처리. switch는 문자열이나 실수가 아닌 정수와 char 타입에서만 작동합니다.
int day = 3;
switch (day) {
case 1: printf("Mon\n"); break;
case 2: printf("Tue\n"); break;
case 3: printf("Wed\n"); break;
case 6:
case 7: printf("Weekend\n"); break;
default: printf("Invalid\n");
}For 루프
for 루프는 init; condition; update를 가집니다. sizeof(nums)/sizeof(nums[0])는 컴파일 타임에 배열 길 이를 계산합니다. for 루프 내부에 i를 선언하려면 C99 이상이 필요합니다. 조건이 처음에 false면 루프 본문은 0번 실행됩니다.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
// Iterate an array
int nums[] = {10, 20, 30};
int n = sizeof(nums) / sizeof(nums[0]);
for (int i = 0; i < n; i++) {
printf("%d\n", nums[i]);
}While & Do-While
while은 실행 전에 확인(0번 실행 가능). do-while은 본문을 먼저 실행한 후 확인(최소 1번 실행). do-while은 조건을 확인하기 전에 프롬프트가 나타나야 하는 입력 검증과 메뉴 루프에 이상적입니다.
int count = 0;
while (count < 3) {
printf("%d\n", count++);
}
int x;
do {
printf("Enter positive: ");
scanf("%d", &x);
} while (x <= 0); // runs at least onceBreak, Continue & goto
break는 가장 가까운 루프/switch를 종료; continue는 다음 반복으로 건너뜁니다. C에는 레이블이 있는 break가 없으므로 깊이 중첩된 루프에서 벗어나는 관용적 방법은 goto입니다. goto는 그 외에는 권장되지 않지만 정리 패턴과 중첩 루프 종료에는 허용됩니다.
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip 3
if (i == 7) break; // stop at 7
printf("%d ", i); // 0 1 2 4 5 6
}
// goto for breaking nested loops
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (found) goto done;
}
}
done: printf("exited\n");함수
정의 & 호출
함수는 사용 전에 선언(프로토타입)되거나 정의되어야 합니다. void 반환 타입은 반환 값이 없음을 의미합니다. const char *name은 함수가 문자열을 수정하지 않음을 의미합니다. C는 값으로 인수 전달; 참조로 전달을 시뮬레이션하려면 포인터를 사용하세요.
int add(int a, int b) {
return a + b;
}
void greet(const char *name) {
printf("Hello, %s!\n", name);
}
int main(void) {
int sum = add(3, 4);
greet("Alice");
return 0;
}재귀
재귀는 더 작은 입력으로 자신을 호출합니다. 모든 재귀 함수는 중지하기 위한 기본 케이스가 필요합니다. 위의 단순 fib는 O(2^n) — 지수적입니다. 효율성을 위해 메모이제이션이나 반복을 사용하세요. 깊은 재귀는 호출 스택을 오버플로우할 수 있습니다.
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
int fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
// factorial(5) == 120함수 포인터
함수 포인터는 함수의 주소를 저장하여 콜백과 동적 디스패치를 가능하게 합니다. int (*op)(int, int) 구문은 두 개의 int를 받아 int를 반환하는 함수에 대한 포인터를 선언합니다. qsort, 이벤트 핸들러, 플러그인 시스템에서 사용됩니다.
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int (*op)(int, int) = add;
printf("%d\n", op(3, 4)); // 7
op = sub;
printf("%d\n", op(3, 4)); // -1
// As a parameter
int apply(int (*f)(int, int), int a, int b) {
return f(a, b);
}가변 인수 함수
가변 인수 함수는 <stdarg.h>를 사용하여 가변 개수의 인수를 받습니다. va_start 초기화, va_arg 다음 인수 검색, va_end 정리. 개수를 아는 방법이 필요합니다(예: 카운트 매개변수나 센티넬 값). printf가 이 방식으로 작동합니다.
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
// sum(3, 10, 20, 30) == 60static & inline
함수/변수에 static은 현재 번역 단위(파일)로 제한합니다. 지역 변수에 static은 호출 간에 유지(전역과 같지만 범위 지정됨). inline은 컴파일러가 함수 본문을 포함하도록 제안; 현대 컴파일러는 무시하고 스스로 결정합니다.
// static: internal linkage (file-local)
static int counter = 0;
static int next_id(void) { return ++counter; }
// inline: hint to expand inline
static inline int square(int x) { return x * x; }
// static local: persists across calls
int call_count(void) {
static int n = 0;
return ++n;
}배열 & 포인터
배열
배열은 고정 크기, 0 인덱스, 메모리에 연속으로 저장됩니다. sizeof(arr)/sizeof(arr[0])는 길이를 계산하지만 포인터가 아닌 실제 배열에서만 작동(배열은 함수에 전달될 때 포인터로 붕괴하여 크기 정보 손실).
int nums[5] = {1, 2, 3, 4, 5};
printf("%d\n", nums[0]); // 1
printf("%d\n", nums[4]); // 5
int len = sizeof(nums) / sizeof(nums[0]); // 5
// Array of strings
char *fruits[] = {"apple", "banana", "cherry"};
printf("%s\n", fruits[1]); // banana포인터
포인터는 메모리 주소를 저장합니다. &는 주소를 가져오고, *는 역참조합니다. 항상 포인터를 초기화(아직 할당되지 않은 경우 NULL 사용). NULL이나 초기화되지 않은 포인터 역참조는 정의되지 않은 동작(보통 크래시). 역참조 전에 NULL 확인.
int x = 10;
int *ptr = &x; // ptr holds address of x
printf("%p\n", (void*)ptr); // address
printf("%d\n", *ptr); // 10 (dereference)
*ptr = 20; // modify x through pointer
printf("%d\n", x); // 20
int *p = NULL; // null pointer (points to nothing)
if (p) { /* safe to dereference */ }포인터 산술
포인터 산술은 요소 크기로 조정: p+1은 다음 바이트가 아닌 다음 요소로 이동. 이는 p[i]를 *(p+i)와 동일하게 만듭니다. 같은 배열에 대한 두 포인터의 빼기는 요소 수를 줍니다. 포인터 산술은 배열 내에서만 유효합니다.
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // points to arr[0]
printf("%d\n", *p); // 10
printf("%d\n", *(p + 1)); // 20
printf("%d\n", *(p + 2)); // 30
p += 3; // now points to arr[3]
printf("%d\n", *p); // 40
int diff = (p - arr); // 3 (number of elements)배열 vs 포인터
배열 이름은 함수에 전달되거나 표현식에 사용될 때 포인터로 붕괴하여 크기 정보를 잃습니다. 이 때문에 배열 길이를 별도로 전달해야 합니다. sizeof(arr)는 arr이 포인터가 아닌 진정한 배열일 때만 전체 배열 크기를 줍니다.
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // arr decays to &arr[0]
// These are equivalent
printf("%d\n", arr[2]);
printf("%d\n", ptr[2]);
printf("%d\n", *(arr + 2));
// But sizeof differs
printf("%zu\n", sizeof(arr)); // 20 (5 * 4 bytes)
printf("%zu\n", sizeof(ptr)); // 8 (pointer size)다차원 배열
2D 배열은 배열의 배열, 행 우선 저장. grid[i][j]는 행 i, 열 j 접근. 함수에 전달할 때 열 수를 지정해야 함: void foo(int arr[][3], int rows). 동적 2D 배열의 경우 포인터 배열을 사용하세요.
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("%d\n", grid[0][1]); // 2
printf("%d\n", grid[1][2]); // 6
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", grid[i][j]);
}
printf("\n");
}구조체 & 공용체
구조체
구조체는 다른 타입의 관련 변수를 그룹화합니다. 멤버는 점 연산자(.)로 접근. 중괄호 표기법으로 초기화. 구조체는 값으로 전달(복사됨); 복사를 피하고 원본을 수정하려면 포인터(struct Point *)로 전달하세요.
struct Point {
int x;
int y;
};
struct Point p = {3, 4};
printf("(%d, %d)\n", p.x, p.y); // (3, 4)
p.x = 10;
p.y = 20;
printf("(%d, %d)\n", p.x, p.y); // (10, 20)typedef
typedef는 타입의 별칭을 생성하여 struct Student 대신 Student를 작성할 수 있습니다. 구조체와 함께 구문을 단순화하는 데 일반적으로 사용됩니다. typedef는 함수 포인터 타입도 별칭을 지정하여 콜백을 훨씬 더 읽기 쉽게 만듭니다.
typedef struct {
char name[50];
int age;
float gpa;
} Student;
Student s = {"Alice", 20, 3.8};
printf("%s: %d, GPA %.1f\n", s.name, s.age, s.gpa);
// typedef for other types
typedef unsigned long ulong;
typedef int (*CompareFn)(const void*, const void*);구조체에 대한 포인터
구조체에 대한 포인터가 있을 때 화살표 연산자(->)로 멤버에 접근하세요. ptr->x는 (*ptr).x의 약어입니다. 효율성(큰 구조체 복사 방지)과 수정을 허용하기 위해 구조체 포인터를 함수에 전달하세요.
typedef struct {
int x, y;
} Point;
Point p = {3, 4};
Point *ptr = &p;
// Arrow operator (->) for pointer members
printf("%d\n", ptr->x); // 3
ptr->y = 10;
printf("%d\n", p.y); // 10
// Equivalent: (*ptr).x공용체
공용체는 같은 메모리에 여러 타입을 겹침 — 한 번에 하나의 멤버만 유효. 한 멤버를 설정하면 다른 멤버를 덮어씀. 타입 펀닝(비트를 다른 타입으로 재해석)과 여러 타입 중 하나만 한 번에 필요할 때 메모리 절약에 유용.
union Value {
int i;
float f;
char bytes[4];
};
union Value v;
v.i = 65;
printf("%d\n", v.i); // 65
printf("%c\n", v.bytes[0]); // 'A' (same memory)
v.f = 3.14f;
printf("%d\n", v.i); // reinterpreted bits!비트 필드 & 열거형
비트 필드는 여러 작은 필드를 단일 int로 패킹하여 메모리 절약(프로토콜과 하드웨어 레지스터에서 일반적). 열거형은 명명된 정수 상수(기본 0, 1, 2...)를 정의. 더 나은 디버깅과 타입 안전을 위해 #define 대신 열거형을 사용하세요.
struct Flags {
unsigned int bold : 1;
unsigned int italic : 1;
unsigned int size : 6; // 0-63
};
struct Flags f = {1, 0, 12};
printf("bold=%d, size=%d\n", f.bold, f.size);
enum Color { RED, GREEN, BLUE };
enum Color c = GREEN;
printf("%d\n", c); // 1메모리 관리
malloc & free
malloc은 힙 메모리를 할당하고 void 포인터(또는 실패 시 NULL)를 반환합니다. 항상 NULL을 확인하세요. 모든 malloc은 메모리 누수를 피하기 위해 free와 짝을 이루어야 합니다. free 후 포인터를 NULL로 설정하면 use-after-free 버그를 방지합니다.
#include <stdlib.h>
int *arr = malloc(5 * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "malloc failed\n");
return 1;
}
for (int i = 0; i < 5; i++) arr[i] = i * 2;
free(arr); // release memory
arr = NULL; // avoid dangling pointercalloc & realloc
calloc은 메모리를 할당하고 0으로 채웁니다(가비지가 있는 malloc보다 안전). realloc은 크기를 조정: 블록 을 이동하여 새 포인터를 반환할 수 있습니다. realloc이 실패하면 NULL을 반환하지만 원래 블록은 여전히 유효 — 누수를 피하기 위해 임시 포인터를 사용하세요.
#include <stdlib.h>
// calloc: zero-initialized
int *arr = calloc(5, sizeof(int)); // all zeros
// realloc: resize
arr = realloc(arr, 10 * sizeof(int));
if (!arr) { /* handle failure, original still valid */ }
free(arr);스택 vs 힙
스택 메모리는 자동(함수 호출로 할당/해제)이고 빠르지만 제한적(종종 1-8 MB). 힙 메모리는 malloc/free로 수동 관리, 훨씬 크지만 느리고 누수 발생. 작고 수명이 짧은 데이터에는 스택; 크거나 수명이 긴 데이터에는 힙을 사용하세요.
// Stack: automatic, fast, limited size
int local_var = 42;
int arr[100]; // on the stack
// Heap: manual, large, slower
int *heap_arr = malloc(1000000 * sizeof(int));
// Stack frame is freed when function returns
// Heap memory persists until explicitly freed메모리 누수 & 댕글링 포인터
메모리 누수는 할당된 메모리에 대한 유일한 포인터를 잃을 때 발생(free 불가). 댕글링 포인터는 해제된 메모리를 가리킴 — 역참조는 정의되지 않은 동작. 이중 해제도 정의되지 않음. Valgrind와 AddressSanitizer 같은 도구가 이 버그를 감지합니다.
// Memory leak: lost the pointer, can't free
void leak(void) {
int *p = malloc(100 * sizeof(int));
// function returns without free -> leaked!
}
// Dangling pointer: using freed memory
int *p = malloc(sizeof(int));
free(p);
*p = 42; // UNDEFINED BEHAVIOR!
// Double free: also undefined
free(p); // crash likely동적 배열 & 문자열
동적 할당은 런타임에 크기가 결정되는 문자열/배열을 생성할 수 있게 합니다. 호출자가 메모리 해제를 담당합니다. 문자열의 경우 항상 strlen+1을 할당(널 종료자). 이 패턴(할당, 반환, 호출자 해제)은 C API에서 일반적입니다.
#include <stdlib.h>
#include <string.h>
// Dynamic string copy
char *dup_str(const char *s) {
char *copy = malloc(strlen(s) + 1); // +1 for null
if (copy) strcpy(copy, s);
return copy; // caller must free
}
char *name = dup_str("Alice");
printf("%s\n", name);
free(name);파일 I/O
fopen & fclose
fopen은 파일을 열고 FILE 포인터(또는 실패 시 NULL)를 반환합니다. 모드: r(읽기), w(쓰기/잘라내기), a(추가), r+(읽기/쓰기), b(바이너리). 항상 NULL을 확인하세요. fclose는 버퍼를 플러시하고 파일을 닫습니다. fgets는 한 줄을 안전하게 읽습니다.
#include <stdio.h>
FILE *f = fopen("data.txt", "r");
if (!f) {
perror("fopen failed");
return 1;
}
char line[256];
while (fgets(line, sizeof(line), f)) {
printf("%s", line);
}
fclose(f);fprintf & fscanf
fprintf와 fscanf는 파일에서 printf/scanf처럼 작동합니다. fscanf는 취약 — 형식 불일치가 문제를 유발. 견고한 파싱을 위해 fgets로 줄을 읽고 sscanf로 파싱하세요. 버퍼를 플러시하고 리소스를 해제하기 위해 항상 완료 후 파일을 닫으세요.
FILE *f = fopen("output.txt", "w");
fprintf(f, "Name: %s\n", "Alice");
fprintf(f, "Age: %d\n", 30);
fclose(f);
FILE *in = fopen("output.txt", "r");
char name[50];
int age;
fscanf(in, "Name: %49s\n", name);
fscanf(in, "Age: %d\n", &age);
printf("%s, %d\n", name, age);
fclose(in);fread & fwrite (바이너리)
fread/fwrite는 원시 바이트를 읽기/쓰기 — 바이너리 데이터와 구조체에 이상적. 인수: 버퍼, 요소 크기, 카운트, 파일. 바이너리 파일은 간결하지만 아키텍처 간 이식성 없음(엔디안, 구조체 패딩). 항상 'b' 모드로 바이너리 파일을 여세요.
typedef struct { int id; float score; } Record;
Record r = {1, 95.5f};
FILE *f = fopen("data.bin", "wb");
fwrite(&r, sizeof(Record), 1, f);
fclose(f);
Record r2;
FILE *in = fopen("data.bin", "rb");
fread(&r2, sizeof(Record), 1, in);
printf("id=%d, score=%.1f\n", r2.id, r2.score);
fclose(in);fseek, ftell & rewind
fseek은 파일 위치 이동: SEEK_SET(시작에서), SEEK_CUR(상대적), SEEK_END(끝에서). ftell은 현재 위치 반환. rewind는 fseek(f, 0, SEEK_SET)의 약어. 이는 파일에서 임의 접근을 가능하게 하여 데이터베이스와 인덱스 조회에 유용.
FILE *f = fopen("data.txt", "r");
fseek(f, 0, SEEK_END); // jump to end
long size = ftell(f); // get position = file size
printf("Size: %ld bytes\n", size);
rewind(f); // back to start
// or: fseek(f, 0, SEEK_SET);
fseek(f, 10, SEEK_SET); // 10 bytes from start
char c = fgetc(f);
printf("Char at 10: %c\n", c);
fclose(f);stderr & 표준 스트림
모든 C 프로그램에는 세 개의 스트림이 있습니다: stdin(키보드), stdout(화면), stderr(화면, 버퍼링 없음). stderr에 에러를 쓰면 정상 출력과 분리되어 리다이렉션 가능: program 2> errors.log. stderr는 버퍼링이 없어 크래시 전에 메시지가 나타납니다.
#include <stdio.h>
// Three standard streams: stdin, stdout, stderr
fprintf(stdout, "Normal output\n");
fprintf(stderr, "Error: something went wrong\n");
int c;
while ((c = fgetc(stdin)) != EOF) {
fputc(c, stdout); // echo input
}
// stderr is unbuffered (appears immediately)
// stdout is line-buffered (flushes on newline)전처리기 & 매크로
#define 상수 & 매크로
#define은 텍스트 치환 매크로를 생성합니다. PI 같은 상수는 가독성과 유지보수성을 향상. 함수형 매크로는 우선순위 버그를 피하기 위해 매개변수를 괄호로 감싸야 함: 괄호 없는 SQUARE(2+3)는 2+3*2+3=11. 매크로보다 const 변수와 inline 함수를 선호하세요.
#define MAX_SIZE 100
#define PI 3.14159
#define VERSION "2.0"
// Function-like macro
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int area = SQUARE(5); // 25
int big = MAX(3, 7); // 7조건부 컴파일
조건부 컴파일(#if, #ifdef, #ifndef)은 컴파일 타임에 코드를 포함/제외합니다. 이는 플랫폼별 코드, 디버그 빌드, 기능 플래그에 사용됩니다. #ifdef는 매크로가 정의되었는지 확인; #if는 값을 평가. #elif와 #else는 대안을 제공.
#define DEBUG 1
#if DEBUG
printf("Debug: x=%d\n", x);
#endif
#ifdef _WIN32
// Windows-specific code
#elif defined(__linux__)
// Linux-specific code
#endif
#ifndef BUFFER_SIZE
#define BUFFER_SIZE 1024
#endifInclude Guard
Include guard는 헤더의 이중 포함을 방지하여 재정의 에러를 피합니다. #ifndef/#define/#endif 패턴이 표준 C. #pragma once는 더 간단하고 널리 지원되는 대안(표준은 아니지만 모든 주요 컴파일러에서 작동).
// myheader.h
#ifndef MYHEADER_H
#define MYHEADER_H
struct Point { int x, y; };
void init_point(struct Point *p);
#endif // MYHEADER_H
// Alternative (non-standard but widely supported):
#pragma once#pragma & 컴파일러 힌트
#pragma는 컴파일러별 지시문을 제공합니다. #pragma once는 더 간단한 include guard. #pragma pack은 구조체 메모리 레이아웃을 제어(바이너리 프로토콜에 중요). __attribute__(GCC/Clang)는 최적화, 사용 중단, 경고를 위해 함수에 주석을 답니다.
#pragma once // include guard
#pragma pack(1) // struct packing (no padding)
#pragma GCC diagnostic ignored "-Wunused-variable"
// Common pragmas
#pragma message("Compiling " __FILE__)
// C99 __attribute__ (GCC/Clang)
__attribute__((deprecated)) void old_func(void);
__attribute__((noreturn)) void fatal(void);문자열화 & 토큰 붙여넣기
#(문자열화)는 매크로 인수를 문자열 리터럴로 변환. ##(토큰 붙여넣기)는 토큰을 새 식별자로 연결. 2단계 STR/XSTR 패턴은 매크로가 문자열화 전에 확장되도록 보장. 코드 생성과 로깅 매크로에 사용됩니다.
#define STR(x) #x
#define XSTR(x) STR(x)
#define CONCAT(a, b) a##b
printf("%s\n", STR(Hello World)); // "Hello World"
printf("%s\n", XSTR(VERSION)); // expands VERSION first
int CONCAT(foo, bar) = 42; // creates variable foobar
printf("%d\n", foobar); // 42비트 연산
기본 비트 연산자
비트 연산자는 개별 비트를 조작합니다. AND(&)는 비트를 마스크(설정된 비트만 유지), OR(|)는 비트 설정, XOR(^)는 비트 토글, NOT(~)은 모든 비트 반전. 왼쪽 시프트(<<)는 2의 거듭제곱으로 곱하고, 오른쪽 시프트(>>)는 나눕니다(부호 없는 경우). 비트 조작에는 항상 부호 없는 타입 사용 — 부호 있는 오른쪽 시프트는 구현 정의(부호 확장 가능). 비트 연산은 매우 빠름(단일 CPU 사이클)이며 플래그, 하드웨어 레지스터, 압축, 암호화에 사용. 바이너리 리터럴(0b 접두사)은 C23/C++14; 오래된 C에서는 16진수(0x) 또는 10진수 사용.
#include <stdio.h>
int main() {
unsigned int a = 0b1100; // 12
unsigned int b = 0b1010; // 10
// AND: both bits must be 1
printf("%u\n", a & b); // 8 (0b1000)
// OR: either bit is 1
printf("%u\n", a | b); // 14 (0b1110)
// XOR: bits differ (exclusive or)
printf("%u\n", a ^ b); // 6 (0b0110)
// NOT: flip all bits
printf("%u\n", ~a); // 4294967283 (on 32-bit)
// Left shift: multiply by 2^n
printf("%u\n", a << 2); // 48 (12 * 4)
// Right shift: divide by 2^n (unsigned)
printf("%u\n", a >> 1); // 6 (12 / 2)
return 0;
}비트 설정, 지우기 & 토글
비트 플래그는 여러 boolean 옵션을 단일 정수로 패킹하여 메모리를 절약합니다. 세 가지 핵심 연산: SET(|= mask), CLEAR(&= ~mask), TOGGLE(^= mask), CHECK(& mask). 읽기 쉬운 플래그 이름을 위해 (1 << n)과 함께 #define 사용. 이 패턴은 시스템 프로그래밍(파일 권한, 장치 제어, 설정 옵션)에서 널리 사용. 예를 들어, Unix 파일 권한(rwxr-xr-x = 0755)은 비트 플래그 사용. 부호 확장 문제를 피하기 위해 항상 부호 없는 정수 사용. bool 배열(플래그당 8비트 대 1비트)보다 메모리 효율적.
#include <stdio.h>
// Flag definitions (powers of 2)
#define FLAG_READ (1 << 0) // 0b0001
#define FLAG_WRITE (1 << 1) // 0b0010
#define FLAG_EXECUTE (1 << 2) // 0b0100
#define FLAG_ADMIN (1 << 3) // 0b1000
int main() {
unsigned int permissions = 0;
// SET a bit (OR with mask)
permissions |= FLAG_READ | FLAG_WRITE; // 0b0011
// CHECK if a bit is set (AND, compare to 0)
if (permissions & FLAG_READ) {
printf("Read permission granted\n");
}
// CLEAR a bit (AND with inverted mask)
permissions &= ~FLAG_WRITE; // 0b0001
// TOGGLE a bit (XOR with mask)
permissions ^= FLAG_EXECUTE; // 0b0101 (execute now on)
permissions ^= FLAG_EXECUTE; // 0b0001 (execute now off)
// SET multiple bits at once
permissions = FLAG_READ | FLAG_EXECUTE | FLAG_ADMIN;
printf("Permissions: 0x%X\n", permissions); // 0xD
return 0;
}비트 조작 트릭
비트 트릭은 속도를 위해 이진 표현을 활용. x & 1은 홀수/짝수 확인(모듈로보다 빠름). x & (x-1)은 최하위 설정 비트를 지움 — 2의 거듭제곱 확인과 비트 카운팅에 유용. __builtin_popcount(GCC/Clang) 또는 __popcnt(MSVC)는 현대 CPU에서 한 명령어로 설정 비트를 셈. XOR 교환(a^=b; b^=a; a^=b)은 임시 변수를 피하지만 현대 CPU에서 느리고 가독성 저하 — 피하세요. '2의 거듭제곱으로 올림' 트릭은 최고 설정 비트를 모든 하위 비트로 전파한 후 1을 더합니다. 이 트릭은 임베디드 시스템, 게임 엔진, 성능 중요 코드에 유용.
#include <stdio.h>
int main() {
int x = 42;
// Check if odd/even (faster than x % 2)
if (x & 1) printf("odd\n"); else printf("even\n");
// Check if power of 2 (only one bit set)
// x & (x-1) clears the lowest set bit
if (x && !(x & (x - 1))) printf("power of 2\n");
// Count set bits (popcount / Hamming weight)
unsigned int n = 0b10110110;
int count = 0;
while (n) { count += n & 1; n >>= 1; }
printf("Set bits: %d\n", count); // 6
// Or use __builtin_popcount(n) (GCC/Clang)
// Swap two values without temp (XOR swap)
int a = 5, b = 10;
a ^= b; b ^= a; a ^= b;
// a=10, b=5 (avoid in practice — less readable)
// Get lowest set bit
unsigned int lowest = x & (-x); // isolates lowest 1-bit
// Round up to next power of 2
unsigned int v = 5;
v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++;
return 0;
}구조체의 비트 필드
비트 필드는 여러 작은 값을 단일 구조체로 패킹하여 메모리를 절약합니다. 콜론 구문(unsigned int field : N)이 비트 너비를 지정. 컴파일러가 비트 추출/삽입을 자동으로 처리. 메모리 제약 시스템, 네트워크 프로토콜, 하드웨어 레지스터 매핑에 유용. 하지만 비트 필드 레이아웃은 구현 정의(바이트 순서, 정렬, 패딩) — 크로스 플랫폼 바이너리 호환성에는 비트 필드를 사용하지 마세요. 이식 가능한 바이너리 형식에는 명시적 비트 마스킹(#define + & |)을 사용. 이름 없는 필드(: 5)는 패딩 추가. 총 크기는 구조체의 정렬로 반올림.
#include <stdio.h>
// Bit fields: pack multiple small fields into one int
struct Date {
unsigned int day : 5; // 0-31 (5 bits)
unsigned int month : 4; // 0-15 (4 bits)
unsigned int year : 12; // 0-4095 (12 bits)
unsigned int is_leap : 1; // 0 or 1 (1 bit)
}; // Total: 22 bits (padded to 32)
struct Flags {
unsigned int visible : 1;
unsigned int editable : 1;
unsigned int locked : 1;
unsigned int : 5; // unnamed padding (5 bits)
unsigned int priority : 4; // 0-15
};
int main() {
struct Date d = { 15, 6, 2024, 0 };
printf("Size: %zu bytes\n", sizeof(d)); // 4 bytes
printf("Date: %u/%u/%u\n", d.day, d.month, d.year);
struct Flags f = { .visible = 1, .editable = 0, .locked = 1, .priority = 7 };
printf("Size: %zu bytes\n", sizeof(f)); // 4 bytes
return 0;
}실용적 비트 조작 (RGB 색상)
여러 값을 하나의 정수로 패킹하는 것은 그래픽, 네트워킹, 임베디드 시스템에서 일반적입니다. RGB 색상은 세 개의 8비트 채널을 24비트(0xRRGGBB)로 패킹. 왼쪽 시프트(<<)가 각 채널을 배치하고, OR(|)가 결합. 오른쪽 시프트(>>)와 마스킹(& 0xFF)이 개별 채널을 추출. 메모리 절약(3바이트 대 1 int)과 원자적 연산 가능. 같은 패턴이 네트워크 바이트 순서, 하드웨어 레지스터 접근, 데이터 압축에 적용. 이식성을 위해 항상 고정 너비 타입(uint8_t, uint32_t) 사용 — int 크기는 플랫폼에 따라 다름.
#include <stdio.h>
#include <stdint.h>
// Pack RGB into a single 32-bit integer (0xRRGGBB)
uint32_t make_color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
// Extract components
uint8_t get_red(uint32_t color) { return (color >> 16) & 0xFF; }
uint8_t get_green(uint32_t color) { return (color >> 8) & 0xFF; }
uint8_t get_blue(uint32_t color) { return color & 0xFF; }
// Blend two colors (50/50 mix)
uint32_t blend(uint32_t c1, uint32_t c2) {
uint8_t r = (get_red(c1) + get_red(c2)) / 2;
uint8_t g = (get_green(c1) + get_green(c2)) / 2;
uint8_t b = (get_blue(c1) + get_blue(c2)) / 2;
return make_color(r, g, b);
}
int main() {
uint32_t red = make_color(255, 0, 0); // 0xFF0000
uint32_t blue = make_color(0, 0, 255); // 0x0000FF
uint32_t purple = blend(red, blue); // 0x7F007F
printf("Red: 0x%06X\n", red);
printf("Blue: 0x%06X\n", blue);
printf("Mix: 0x%06X (R=%d G=%d B=%d)\n",
purple, get_red(purple), get_green(purple), get_blue(purple));
return 0;
}시그널 처리
기본 시그널 처리
시그널은 프로세스에 보내지는 소프트웨어 인터럽트(예: Ctrl+C는 SIGINT 전송, 0으로 나누기는 SIGFPE 전송). signal()은 핸들러 함수를 등록. 핸들러 내에서는 async-signal-safe 함수만 허용 — printf, malloc, 대부분의 stdlib 함수는 안전하지 않음(메인 프로그램이 호출 중간에 중단될 수 있음). 출력에는 write() 사용. 일반 시그널: SIGINT(Ctrl+C), SIGTERM(종료 요청), SIGKILL(강제 종료, catch 불가), SIGSEGV(세그폴트), SIGALRM(타이머). 이식성과 제어를 위해 signal()보다 sigaction()을 선호.
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
// Signal handler function (must match signature)
void handler(int sig) {
// WARNING: only async-signal-safe functions allowed here!
// printf is NOT safe — use write() instead
const char *msg = "Caught SIGINT\n";
write(STDOUT_FILENO, msg, 14);
}
int main() {
// Register handler for Ctrl+C (SIGINT)
signal(SIGINT, handler);
// Ignore SIGINT entirely
// signal(SIGINT, SIG_IGN);
// Reset to default behavior (terminate)
// signal(SIGINT, SIG_DFL);
printf("PID %d waiting. Press Ctrl+C...\n", getpid());
while (1) {
sleep(1);
}
return 0;
}sigaction (이식 가능한 시그널 처리)
sigaction()은 현대적이고 이식 가능한 시그널 처리 방법(signal() 동작은 플랫폼에 따라 다름). sa_sigaction 핸들러는 세부 정보가 있는 siginfo_t를 받음: si_pid(전송자 PID), si_uid(전송자 UID), si_signo(시그널 번호), si_code(이유). SA_SIGINFO 플래그는 3인수 핸들러를 활성화. sa_mask는 핸들러 실행 중 특정 시그널을 차단(중첩 인터럽트 방지). 기타 플래그: SA_RESTART(중단된 시스템 콜 자동 재시작), SA_NOCLDWAIT(좀비 자식 없음). 프로덕션 코드에는 항상 sigaction() 사용 — signal()은 일부 플랫폼에서 신뢰할 수 없음.
#include <stdio.h>
#include <signal.h>
#include <string.h>
void handler(int sig, siginfo_t *info, void *context) {
// siginfo_t provides details about the signal
printf("Signal %d from PID %d\n", sig, info->si_pid);
}
int main() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = handler; // use sa_sigaction (not sa_handler)
sa.sa_flags = SA_SIGINFO; // enable siginfo_t parameter
// Block other signals during handler execution
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGQUIT); // block SIGQUIT during handler
// Register (more portable than signal())
sigaction(SIGINT, &sa, NULL);
// Send a signal to self
raise(SIGINT); // like kill(getpid(), SIGINT)
printf("Done\n");
return 0;
}시그널 전송 & 알람
alarm(seconds)는 지정된 시간 후 SIGALRM 예약 — 타임아웃에 유용. pause()는 시그널이 도착할 때까지 차단. volatile sig_atomic_t는 시그널 핸들러와 메인 코드 간에 데이터를 공유하는 유일한 안전한 방법 — volatile은 컴파일러 최적화를 방지, sig_atomic_t는 원자적 접근을 보장. kill(pid, signal)은 다른 프로세스에 시그널 전송. raise(sig)는 자신에게 시그널 전송. SIGKILL(9)과 SIGSTOP은 catch하거나 무시할 수 없음 — 항상 작동. SIGTERM(15)은 정중한 종료 요청(프로그램이 정리하기 위해 catch 가능). 단순 타임아웃에는 alarm() 사용; 더 많은 제어를 위해 setitimer()/timer_create() 사용.
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
volatile sig_atomic_t got_alarm = 0;
void alarm_handler(int sig) {
got_alarm = 1; // safe: sig_atomic_t is atomic
}
int main() {
signal(SIGALRM, alarm_handler);
// Set a timer: deliver SIGALRM after 3 seconds
alarm(3);
printf("Waiting for alarm...\n");
// Wait for the alarm
while (!got_alarm) {
pause(); // sleep until any signal arrives
}
printf("Alarm fired!\n");
// Send signal to another process
// kill(pid, SIGTERM); // request termination
// kill(pid, SIGKILL); // force kill (can't be caught)
// Send signal to self
raise(SIGUSR1);
return 0;
}일반 시그널 참조
시그널 이해는 Unix 프로그래밍에 필수. SIGKILL(9)과 SIGSTOP은 catch 불가 — 최후의 수단. SIGTERM은 표준 우아한 종료 시그널(상태 저장을 위해 catch). SIGINT는 Ctrl+C(대화형 인터럽트). SIGCHLD는 자식이 종료할 때 발생 — wait()하지 않으면 자식이 좀비가 됨. SIGCHLD를 SIG_IGN으로 설정하면 커널이 자동 수거(또는 SA_NOCLDWAIT 사용). SIGPIPE는 닫힌 파이프/소켓에 쓸 때 발생 — 대부분의 서버는 이를 무시(signal(SIGPIPE, SIG_IGN))하고 write() 반환 값을 확인. 시그널 핸들러에서는 exit()(atexit 핸들러 실행, 시그널 안전하지 않을 수 있음)가 아닌 _exit() 사용.
#include <signal.h>
// Common POSIX signals:
// SIGINT (2) - Ctrl+C interrupt (terminate)
// SIGQUIT (3) - Ctrl+\ quit (core dump)
// SIGKILL (9) - Force kill (CANNOT be caught/ignored)
// SIGSEGV (11) - Segmentation fault (invalid memory access)
// SIGPIPE (13) - Write to broken pipe
// SIGTERM (15) - Termination request (graceful shutdown)
// SIGSTOP (19) - Pause process (CANNOT be caught/ignored)
// SIGCONT (18) - Resume paused process
// SIGCHLD (17) - Child process exited
// SIGALRM (14) - Timer alarm
// SIGUSR1 (10) - User-defined signal 1
// SIGUSR2 (12) - User-defined signal 2
// SIGFPE (8) - Arithmetic error (divide by zero)
// SIGBUS (7) - Bus error (misaligned access)
// Graceful shutdown pattern:
void cleanup_handler(int sig) {
// Save state, close files, release resources
// Then exit cleanly
_exit(0); // use _exit in signal handlers (not exit)
}
// In main:
signal(SIGTERM, cleanup_handler);
signal(SIGINT, cleanup_handler);
// Prevent zombie children:
signal(SIGCHLD, SIG_IGN); // auto-reap childrenSelf-Pipe 트릭 (시그널 안전 웨이크업)
Self-pipe 트릭은 근본적인 문제를 해결: 시그널 핸들러는 안전하게 복잡한 작업을 할 수 없지만, 메인 루프에서 시그널에 응답해야 함. 해결책: 핸들러가 파이프에 바이트를 쓰고, 메인 루프는 select()/poll()로 감지. 이는 시그널을 이벤트 루프에 안전하게 통합. 핸들러는 write()만 호출(async-signal-safe). 현대 대안: signalfd()(Linux별, 시그널을 파일 디스크립터로 직접 변환) 또는 pselect()(select 중 원자적으로 시그널 차단). 이 패턴은 이벤트 구동 서버(nginx, Redis)에서 경쟁 조건 없이 시그널을 처리하는 데 사용.
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
int pipe_fd[2]; // [0]=read, [1]=write
void handler(int sig) {
// Write one byte to the pipe — wakes up select()/poll()
write(pipe_fd[1], &sig, sizeof(sig));
}
int main() {
pipe(pipe_fd);
// Make read end non-blocking
fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK);
signal(SIGINT, handler);
signal(SIGTERM, handler);
printf("Waiting (select-based)...\n");
while (1) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(pipe_fd[0], &readfds);
// select() blocks until pipe is writable (signal received)
int ready = select(pipe_fd[0] + 1, &readfds, NULL, NULL, NULL);
if (ready > 0 && FD_ISSET(pipe_fd[0], &readfds)) {
int sig;
read(pipe_fd[0], &sig, sizeof(sig));
printf("Handled signal %d in main loop\n", sig);
if (sig == SIGTERM) break;
}
}
return 0;
}프로세스 Fork & Exec
fork() 기본
fork()는 현재 프로세스의 정확한 복사본을 생성 — 유일한 차이는 반환 값: 자식에서 0, 부모에서 자식의 PID. 두 프로세스 모두 fork() 호출에서 계속. 자식은 부모의 메모리 복사본을 받음(copy-on-write가 이를 최적화). 세 가지 경우를 항상 확인: pid < 0(에러), pid == 0(자식), pid > 0(부모). waitpid()는 자식이 종료할 때까지 차단하고 상태를 검색. WIFEXITED는 정상 종료 확인, WEXITSTATUS는 종료 코드 가져오기. wait()하지 않으면 자식이 수거될 때까지 좀비가 됨.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork(); // create a child process
if (pid < 0) {
perror("fork failed");
return 1;
} else if (pid == 0) {
// CHILD process (fork returned 0)
printf("Child: PID=%d, Parent PID=%d\n",
getpid(), getppid());
sleep(2);
printf("Child exiting\n");
return 42; // child exit code
} else {
// PARENT process (fork returned child's PID)
printf("Parent: PID=%d, Child PID=%d\n",
getpid(), pid);
int status;
waitpid(pid, &status, 0); // wait for child
if (WIFEXITED(status)) {
printf("Child exited with code %d\n",
WEXITSTATUS(status));
}
}
return 0;
}exec 패밀리 (프로세스 이미지 교체)
exec는 현재 프로세스 이미지를 새 프로그램으로 교체 — PID는 동일하게 유지되지만 코드, 데이터, 스택이 교체. exec는 실패 시에만 반환. 명명 규칙: 'l' = 인수 목록(가변, NULL 종료), 'v' = 인수 벡터/배열, 'p' = 실행 파일을 위해 PATH 검색, 'e' = 사용자 정의 환경. 첫 번째 인수는 관례적으로 프로그램 이름(argv[0]). fork()+exec()는 Unix에서 프로그램을 시작하는 방식 — fork가 프로세스를 생성, exec가 새 프로그램을 로드. 이 분리는 fork와 exec 사이에 파일 디스크립터, 환경, 시그널 설정을 가능하게.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// CHILD: replace self with a new program
// exec never returns on success (only on failure)
// execlp: search PATH, list arguments
execlp("ls", "ls", "-la", "/tmp", NULL);
// execvp: search PATH, array of arguments
char *args[] = {"ls", "-la", "/tmp", NULL};
execvp("ls", args);
// execl: full path, list arguments
execl("/bin/ls", "ls", "-la", NULL);
// Only reached if exec failed
perror("exec failed");
_exit(1);
} else {
wait(NULL); // parent waits for child
printf("Child finished\n");
}
return 0;
}
// exec variants:
// execl (path, arg1, arg2, ..., NULL) — list args, full path
// execlp (file, arg1, arg2, ..., NULL) — list args, search PATH
// execv (path, argv[]) — array args, full path
// execvp (file, argv[]) — array args, search PATH
// execve (path, argv[], envp[]) — array args, custom env좀비 & 고아 프로세스
좀비는 자식이 종료했지만 부모가 wait()를 호출하지 않았을 때 발생 — 커널은 수거될 때까지 프로세스 테이블 항목(PID, 종료 상태)을 유지. 좀비는 PID를 낭비하고 프로세스 테이블을 고갈시킬 수 있음. 해결: 항상 자식을 wait(), 또는 SIGCHLD를 SIG_IGN으로 설정(커널이 자동 수거). 고아는 부모가 자식보다 먼저 종료할 때 발생 — init/systemd(PID 1)이 고아를 입양하고 종료 시 수거. 이중 fork 패턴(fork, 자식이 다시 fork, 첫 번째 자식 종료)은 init에 자동으로 재부모되어 터미널에서 분리된 데몬을 생성. 'ps aux | grep Z' 또는 'top'으로 좀비 모니터링.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
printf("Child PID=%d\n", getpid());
_exit(0); // child exits immediately
}
// If parent doesn't wait(), child becomes a ZOMBIE
// (process table entry remains until reaped)
sleep(5); // parent sleeps — child is now a zombie
// Run 'ps' during this window to see the zombie (state 'Z')
// Reap the zombie:
int status;
waitpid(pid, &status, 0);
printf("Zombie reaped\n");
// Orphan: if parent exits before child
pid_t pid2 = fork();
if (pid2 == 0) {
sleep(3); // parent will exit first
printf("Orphan adopted by init (PID 1), new parent=%d\n",
getppid());
_exit(0);
}
// Parent exits immediately — child becomes orphan
// init/systemd (PID 1) adopts and reaps it
// Prevent zombies: ignore SIGCHLD
// signal(SIGCHLD, SIG_IGN); // kernel auto-reaps children
// Or use SA_NOCLDWAIT with sigaction
return 0;
}데몬 프로세스 생성
데몬은 터미널 없이 실행되는 백그라운드 프로세스(예: 웹 서버, 데이터베이스). 데몬화 단계: 셸에서 분리하기 위해 fork+exit, setsid()로 새 세션 생성(제어 터미널 없음), 안전을 위해 다시 fork, 파일 시스템을 잡지 않도록 chdir('/'), 예측 가능한 파일 권한을 위해 umask 설정, stdio를 /dev/null로 닫기/리다이렉트. 이중 fork는 open()을 통해 데몬이 터미널을 재획득하는 것을 방지하는 Unix 관례. 현대 시스템은 데몬 관리를 위해 systemd 서비스 파일을 제공하지만, 수동 데몬화 이해는 임베디드 시스템과 이식 가능한 코드에 여전히 중요. stdout이 /dev/null이므로 파일에 로그.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
void daemonize() {
// 1. Fork and exit parent (child continues in background)
pid_t pid = fork();
if (pid > 0) exit(0); // parent exits
if (pid < 0) exit(1);
// 2. Create new session (detach from controlling terminal)
setsid();
// 3. Fork again (prevent reacquiring a terminal)
pid = fork();
if (pid > 0) exit(0);
if (pid < 0) exit(1);
// 4. Change working directory to / (don't hold filesystem)
chdir("/");
// 5. Set umask to 0 (full control over file permissions)
umask(0);
// 6. Close standard file descriptors (detach from terminal)
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// 7. Redirect them to /dev/null (in case code writes to them)
open("/dev/null", O_RDWR); // fd 0 = stdin
dup(0); // fd 1 = stdout
dup(0); // fd 2 = stderr
}
int main() {
daemonize();
// Now running as a daemon (background, no terminal)
while (1) {
// Daemon work here (e.g., log to file, listen on socket)
sleep(60);
}
return 0;
}프로세스 간 통신 (IPC) 개요
IPC는 프로세스가 통신하게 함. 파이프는 가장 단순(부모-자식, 단방향). 명명된 파이프(FIFO)는 파일 시스템 경로를 통해 관련 없는 프로세스 간 작동. 공유 메모리는 가장 빠름(제로 카피)하지만 동기화 필요(세마포어/뮤텍스). 소켓은 가장 유연(양방향, 네트워크 가능). 메시지 큐는 구조화된, 메시지 경계 통신 제공. 시그널은 최소(단지 숫자). 필요에 따라 선택: 단순 부모-자식에는 파이프, 고성능 데이터 공유에는 공유 메모리, 네트워크 통신에는 소켓. System V IPC(shmget, semget)는 오래됨; POSIX IPC(shm_open, sem_open)는 더 깔끔하지만 보편적으로 사용 가능하지는 않음.
#include <stdio.h>
// C provides several IPC mechanisms:
// 1. PIPES: unidirectional byte stream between parent/child
// pipe(fd) creates fd[0]=read, fd[1]=write
// Only works between related processes (fork)
// 2. NAMED PIPES (FIFOs): like pipes but have a filesystem path
// mkfifo("/tmp/myfifo", 0666);
// Works between unrelated processes
// 3. SHARED MEMORY: fastest IPC (both processes access same RAM)
// shmget/shmat (System V) or shm_open/mmap (POSIX)
// 4. MESSAGE QUEUES: structured messages (not byte stream)
// msgget/msgsnd/msgrcv (System V) or mq_open (POSIX)
// 5. SEMAPHORES: synchronization (not data transfer)
// semget/semop (System V) or sem_open (POSIX)
// 6. SOCKETS: bidirectional, works across machines (network)
// socket/bind/listen/accept/connect
// 7. SIGNALS: minimal data (just signal number)
// kill(pid, SIGUSR1)
// Choosing IPC:
// - Same machine, related processes → pipes
// - Same machine, unrelated processes → named pipes, shared memory
// - Different machines → sockets
// - Need synchronization → semaphores, mutexes
// - Need structured messages → message queues파이프 & IPC
익명 파이프 (부모-자식)
파이프는 관련 프로세스(fork로 생성) 간 단방향 통신을 제공. pipe(fd)는 두 개의 파일 디스크립터 생성: fd[0]은 읽기, fd[1]은 쓰기. 중요: 각 프로세스에서 사용하지 않는 끝을 닫기 — 부모는 읽기 끝을 닫고, 자식은 쓰기 끝을 닫음. 쓰기 끝이 닫히지 않으면 자식의 read()는 영원히 차단(더 많은 데이터 대기). read()는 모든 쓰기 끝이 닫힐 때만 0(EOF) 반환. 파이프는 고정 버퍼(일반적으로 64KB) — 버퍼가 가득 차면 write() 차단. 파이프는 부모-자식 통신과 셸 명령 파이핑(ls | grep)에 이상적.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main() {
int fd[2]; // fd[0]=read end, fd[1]=write end
pipe(fd); // create pipe
pid_t pid = fork();
if (pid == 0) {
// CHILD: read from pipe
close(fd[1]); // close unused write end
char buf[256];
int n = read(fd[0], buf, sizeof(buf));
buf[n] = '\0';
printf("Child received: %s", buf);
close(fd[0]);
} else {
// PARENT: write to pipe
close(fd[0]); // close unused read end
const char *msg = "Hello from parent!\n";
write(fd[1], msg, strlen(msg));
close(fd[1]); // close write end → child's read returns 0 (EOF)
wait(NULL);
}
return 0;
}명명된 파이프 (FIFO)
명명된 파이프(FIFO)는 파일 시스템 이름이 있는 파이프 — 관련 없는 프로세스 간 작동. mkfifo()가 파이프 파일 생성; open()은 리더와 라이터가 모두 연결될 때까지 차단(내장 동기화). FIFO는 unlink()될 때까지 지속(프로세스가 종료되면 사라지는 익명 파이프와 달리). 별도 프로그램 간 단순 IPC에 유용. open()의 차단 동작은 리더가 준비될 때까지 라이터가 시작하지 않도록 보장. 비차단 열기를 위해 O_NONBLOCK 사용. FIFO는 단방향 — 양방향 통신에는 두 개의 FIFO나 소켓 사용. 명명된 파이프는 셸 스크립트와 시스템 서비스에서 일반적으로 사용.
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
// Process A (writer):
int writer_main() {
mkfifo("/tmp/myfifo", 0666); // create named pipe
int fd = open("/tmp/myfifo", O_WRONLY);
write(fd, "Hello via FIFO!", 15);
close(fd);
return 0;
}
// Process B (reader) — can be a completely separate program:
int reader_main() {
int fd = open("/tmp/myfifo", O_RDONLY);
char buf[256];
int n = read(fd, buf, sizeof(buf));
buf[n] = '\0';
printf("Received: %s\n", buf);
close(fd);
return 0;
}
// Named pipes persist in the filesystem (use unlink to remove):
// unlink("/tmp/myfifo");
// open() blocks until BOTH a reader and writer are connected
// (unless O_NONBLOCK is used)공유 메모리 (가장 빠른 IPC)
공유 메모리는 가장 빠른 IPC — 두 프로세스가 같은 물리적 RAM을 매핑하여 데이터 전송이 제로 카피. shmget()이 세그먼트 생성, shmat()이 프로세스의 주소 공간에 부착, shmdt()가 분리, shmctl(IPC_RMID)가 파괴. 중요한 주의: 공유 메모리는 동기화를 제공하지 않음 — 두 프로세스가 동시에 접근하면 데이터 경쟁 발생. 접근을 조정하기 위해 세마포어, 뮤텍스 또는 다른 동기화를 반드시 사용. ftok()가 파일 경로에서 키 생성(두 프로세스가 키에 동의해야 함). 완료 시 항상 공유 메모리 파괴(프로세스 종료 후에도 지속되어 메모리 누수). POSIX 공유 메모리(shm_open/mmap)는 더 깔끔한 대안.
#include <stdio.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <string.h>
#include <unistd.h>
#define SHM_SIZE 1024
int main() {
key_t key = ftok("/tmp/shmfile", 65); // generate unique key
// Create shared memory segment
int shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT);
pid_t pid = fork();
if (pid == 0) {
// CHILD: attach and read
char *shared = (char *)shmat(shmid, NULL, 0);
sleep(1); // wait for parent to write
printf("Child reads: %s\n", shared);
shmdt(shared); // detach
} else {
// PARENT: attach and write
char *shared = (char *)shmat(shmid, NULL, 0);
strcpy(shared, "Hello from shared memory!");
printf("Parent wrote to shared memory\n");
shmdt(shared);
wait(NULL);
// Destroy shared memory after use
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}
// WARNING: shared memory has NO synchronization!
// Use semaphores or mutexes to prevent race conditions.dup2 & 리다이렉션
dup2(oldfd, newfd)는 newfd를 oldfd의 복사본으로 만듦 — 이것이 셸 리다이렉션의 작동 방식. stdout을 파이프로 리다이렉트: dup2(pipe_write, STDOUT_FILENO) — 이제 stdout으로의 printf/write가 파이프로 감. stdin을 파이프에서 리다이렉트: dup2(pipe_read, STDIN_FILENO) — 이제 stdin에서의 scanf/read가 파이프에서 옴. 이것이 셸이 파이프(ls | sort), 리다이렉션(ls > file), 입력(sort < file)을 구현하는 정확한 방식. dup2 후 원래 fd를 닫으세요(복제됨). 이 패턴은 Unix 파이프라인을 프로그래밍 방식으로 구축하는 데 근본적이며 셸, popen(), 프로세스 관리 라이브러리에서 사용.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
// Implement shell-like pipeline: ls | sort
int main() {
int pipefd[2];
pipe(pipefd);
pid_t pid1 = fork();
if (pid1 == 0) {
// First child: ls (writes to pipe instead of stdout)
close(pipefd[0]); // close read end
dup2(pipefd[1], STDOUT_FILENO); // stdout → pipe write
close(pipefd[1]); // close original (dup'd)
execlp("ls", "ls", NULL);
}
pid_t pid2 = fork();
if (pid2 == 0) {
// Second child: sort (reads from pipe instead of stdin)
close(pipefd[1]); // close write end
dup2(pipefd[0], STDIN_FILENO); // stdin → pipe read
close(pipefd[0]); // close original (dup'd)
execlp("sort", "sort", NULL);
}
// Parent: close both ends and wait
close(pipefd[0]);
close(pipefd[1]);
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
return 0;
}popen (고급 파이프)
popen()은 fork+pipe+exec+shell의 고급 래퍼 — /bin/sh를 통해 명령을 실행하고 출력 읽기('r') 또는 입력 쓰기('w')를 위해 FILE*을 반환. 수동 fork/pipe/exec보다 훨씬 단순하지만 셸을 통해 실행되므로 신뢰할 수 없는 입력을 절대 전달하지 마세요(셸 인젝션 위험). 반환된 FILE*에서 일반 파일처럼 fgets/fprintf 사용. pclose()가 파이프를 닫고 자식이 종료될 때까지 대기(상태 반환). 신뢰할 수 없는 입력의 경우 직접 fork+execvp 사용(셸 없음). popen은 빠른 스크립트, 시스템 관리 도구, 명령 출력 읽기에 완벽. 양방향 통신의 경우 socketpair() 또는 두 개의 파이프 사용.
#include <stdio.h>
#include <stdlib.h>
int main() {
// popen opens a process with a pipe (like shell command | ...)
FILE *fp = popen("ls -la /tmp", "r");
if (fp == NULL) {
perror("popen failed");
return 1;
}
// Read command output line by line
char buf[256];
while (fgets(buf, sizeof(buf), fp) != NULL) {
printf(">> %s", buf);
}
pclose(fp); // closes pipe and waits for child
// Writing to a process (like ... | command):
FILE *wp = popen("grep hello", "w");
fprintf(wp, "hello world\n");
fprintf(wp, "goodbye\n");
pclose(wp); // grep outputs "hello world"
return 0;
}
// popen is simpler than fork+pipe+exec but:
// - Runs via /bin/sh (shell injection risk with user input!)
// - Less control over the child process
// - Use fork+exec directly for untrusted inputMakefile & 빌드 도구
기본 Makefile 구조
Make는 컴파일을 자동화. Makefile은 규칙으로 구성: target(빌드할 파일), prerequisites(의존성), recipe(셸 명령, TAB 들여쓰기). 변수(CC, CFLAGS)가 설정을 중앙화. 자동 변수: $@(target 이름), $<(첫 번째 전제조건), $^(모든 전제조건). 패턴 규칙(%.o: %.c)이 모든 소스 파일에 대한 컴파일을 일반화. .PHONY는 파일이 아닌 target(clean, all, install)을 선언. 첫 번째 규칙이 기본(인수 없는 make는 'all' 빌드). Make는 파일 타임스탬프를 추적 — 전제조건이 target보다 최신인 경우에만 재빌드. 이 증분 빌드는 큰 프로젝트에서 시간을 절약.
# Makefile — build automation for C/C++ projects
# Rule syntax: target: prerequisites
# recipe (must start with TAB, not spaces)
# Variables
CC = gcc
CFLAGS = -Wall -Wextra -g -O2
TARGET = myapp
SRCS = main.c utils.c parser.c
OBJS = $(SRCS:.c=.o) # substitute .c with .o
# Default target (first rule)
all: $(TARGET)
# Link object files into executable
$(TARGET): $(OBJS)
$(CC) $(CFLAGS) -o $@ $^
# Compile each .c to .o
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
# Clean build artifacts
clean:
rm -f $(OBJS) $(TARGET)
# Run the program
run: $(TARGET)
./$(TARGET)
# Phony targets (not files)
.PHONY: all clean run
# Usage:
# $ make — builds 'all' (the default)
# $ make clean — removes build files
# $ make run — builds and runs
# $ make -j4 — parallel build (4 jobs)자동 변수 & 패턴 규칙
자동 변수는 Makefile을 간결하고 유지보수 가능하게 만듭니다. $@(target), $<(첫 번째 전제조건), $^(모든 전제조건)가 가장 일반적. 패턴 규칙(%.o: %.c)은 모든 소스 파일에 대해 하나의 규칙을 작성하게 함 — %는 임의의 문자열과 일치. $(wildcard)는 글로브와 일치하는 파일을 찾고, $(patsubst)는 문자열을 변환 — 함께 소스를 자동 발견. @ 접두어는 명령 에코를 억제. 정적 패턴 규칙(target: %.o: %.c)은 특정 목록에 적용. 이 기능을 이해하면 반복적인 규칙을 제거하고 Makefile을 큰 프로젝트로 확장. recipe 들여쓰기에는 항상 공백이 아닌 TAB 사용 — Make는 이에 대해 엄격.