dup - whdlgp/system_programming_pra GitHub Wiki

๊ฐ™์€ ํŒŒ์ผ ์ •๋ณด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์„œ๋กœ๋‹ค๋ฅธ ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ

์ด์ „์— ์–ธ๊ธ‰ํ•œ ํ•˜๋“œ๋งํฌ์™€ ๋น„์Šทํ•˜๋‹ค๋ฉด ๋น„์Šทํ•œ ๋Š๋‚Œ์ด๋‹ค. ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ fd1์„ ๋งŒ๋“ค๊ณ , fd1์€ ํŒŒ์ผ1์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค๊ณ  ํ•˜์ž. ๊ทธ๋Ÿฐ๋Œ€ fd2 ๋„ ํŒŒ์ผ1์„ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด? ๋ญ ์ด๋Ÿฐ ๊ฒƒ๋“ค์„ ํ•˜๊ณ ์‹ถ๋‹ค๋Š” ์†Œ๋ฆฌ๋‹ค.

์‰ฝ๊ฒŒ ๋งํ•ด ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ๋ฅผ ๋ณต์‚ฌํ•˜๊ฒ ๋‹ค๋Š” ์†Œ๋ฆฌ

dup

dup(์›๋ž˜ ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ)

๋ฆฌํ„ด๊ฐ’์€ '์›๋ž˜ ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ'์™€ ๊ฐ™์€ ์ •๋ณด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ๋‹ค.

dup2

dup2(ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ1, ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ2)

'ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ1' ์ด ๊ฐ€๋ฆฌํ‚ค๋Š” ์ •๋ณด๋ฅผ, ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ2๋„ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค.

dup2.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
	int fd1, fd2, fd3;
	char c1, c2, c3;
	char *fname = argv[1];

	fd1 = open(fname, O_RDONLY);
	fd2 = open(fname, O_RDONLY);
	fd3 = open(fname, O_RDONLY);

	dup2(fd2, fd3);

	read(fd1, &c1, 1);
	read(fd2, &c2, 1);
	read(fd3, &c3, 1);

	printf("c1 = %c, c2 = %c, c3 = %c", c1, c2, c3);

	return 0;
}
./dup2 data.txt   
c1 = a, c2 = a, c3 = b%  

data.txt์—๋Š” "abcde" ๋ผ๋Š” ์ •๋ณด๊ฐ€ ์ €์žฅ๋˜์–ด์žˆ๋‹ค.
fd2์™€ fd3์€ ๊ฐ™์€ ์ •๋ณด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค. ์‰ฝ๊ฒŒ๋งํ•ด fd2์™€ fd3๋Š” ์‚ฌ์‹ค์ƒ ๊ฐ™์€ ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ๋‹ค.

  • ์ฒซ๋ฒˆ์งธ read ์—์„œ fd1 ๋ฅผ ์ฝ์„ ๋•Œ, data.txt์˜ ์ฒซ๋ฒˆ์งธ ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ๋Š”๋‹ค.
  • ๋‘๋ฒˆ์งธ read ์—์„œ fd2 ๋ฅผ ์ฝ์„ ๋•Œ, data.txt์˜ ์ฒซ๋ฒˆ์งธ ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ๋Š”๋‹ค.
  • ์„ธ๋ฒˆ์งธ read ์—์„œ fd3 ๋ฅผ ์ฝ์„ ๋•Œ, fd2๋ฅผ ์ฝ์„๋•Œ ์ฝ๊ธฐ/์“ฐ๊ธฐ ์œ„์น˜ ํฌ์ธํ„ฐ๊ฐ€ ์ด๋™ํ–ˆ์œผ๋ฏ€๋กœ ๋‘๋ฒˆ์งธ ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ๋Š”๋‹ค. ๊ทธ๋ž˜์„œ ์ถœ๋ ฅ์€ a, a, b ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅ๋œ๋‹ค.
	read(fd1, &c1, 1);
	read(fd2, &c2, 1);
	read(fd3, &c3, 1);

์ด ๊ตฌ๋ฌธ์„

	read(fd1, &c1, 1);
	read(fd2, &c2, 1);
	read(fd2, &c3, 1); //fd2 ๋กœ ๋ณ€๊ฒฝํ•ด๋ด„

์™€ ๊ฐ™์ด ๋ฐ”๊พผ ํ›„ ์ถœ๋ ฅ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด dup2 ๊ฐ€ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š”์ง€ ์ดํ•ดํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋‹ค.

โš ๏ธ **GitHub.com Fallback** โš ๏ธ