๐ป[C#]IPC ํต์ ํ๊ตฌ (Shared Memory)-2
๐ ๊ฐ๋ฐ ํ๊ฒฝ
๐ MemoryMappedFile
์ค์ต์ ๋ค์ด๊ฐ๊ธฐ์ ์์ MSDN ์ ์ฐธ์กฐํ ๊ฒฐ๊ณผ Shared Memory๋ฅผ ๊ตฌํํ๊ธฐ์ํด MemoryMappedFile์ ์ด์ฉํ๋ค๋๋ผโฆ ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ์ฌ์ฉํ๊ธฐ ์ํ ํด๋์ค์ด๋ฉฐ ํ์ผ ๋ด์ฉ์ ์ ํ๋ฆฌ์ผ์ด์
๋
ผ๋ฆฌ์ ์ฃผ์ ๊ณต๊ฐ์ ๋งคํํ๋ค. ์ค๋์ ์ด ๋
์์ ํํด์ณ ๋ณด์!
| Method | Description |
|---|---|
CreateNew(String, Int64) | ์์คํ ๋ฉ๋ชจ๋ฆฌ์์ ์ง์ ๋ ์ฉ๋์ ๊ฐ์ง ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ๋ง๋ญ๋๋ค. |
CreateNew(String, Int64, MemoryMappedFileAccess) | ์์คํ ๋ฉ๋ชจ๋ฆฌ์์ ์ง์ ๋ ์ฉ๋๊ณผ ์ก์ธ์ค ํ์์ ๊ฐ์ง ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ๋ง๋ญ๋๋ค. |
CreateNew(String, Int64, MemoryMappedFileAccess, MemoryMappedFileOptions, HandleInheritability) | ์ง์ ๋ ์ด๋ฆ, ์ฉ๋, ์ก์ธ์ค ํ์, ๋ฉ๋ชจ๋ฆฌ ํ ๋น ์ต์ ๋ฐ ์์์ ๊ฐ์ง ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ๋ง๋ญ๋๋ค. |
๊ทธ๋ฆฌ๊ณ ๋ฐ์ดํฐ๋ฅผ ์ฝ๊ธฐ ์ํด MemoryMappedViewAccessor ์ ์ฌ์ฉํ๋ค.
| Method | Description |
|---|---|
CreateViewAccessor() | ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ๋ทฐ์ ๋งคํ๋๋ MemoryMappedViewAccessor๋ฅผ ๋ง๋ญ๋๋ค. |
CreateViewAccessor(Int64, Int64) | ์ง์ ๋ ์คํ์
๊ณผ ํฌ๊ธฐ๋ฅผ ๊ฐ์ง๊ณ ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ๋ทฐ์ ๋งคํ๋๋ MemoryMappedViewAccessor๋ฅผ ๋ง๋ญ๋๋ค. |
CreateViewAccessor(Int64, Int64, MemoryMappedFileAccess) | ์ง์ ๋ ์คํ์
, ํฌ๊ธฐ ๋ฐ ์ก์ธ์ค ์ ํ์ ๊ฐ์ง๊ณ ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ๋ทฐ์ ๋งคํ๋๋ MemoryMappedViewAccessor๋ฅผ ๋ง๋ญ๋๋ค. |
๐ฅ๏ธ Shared Memory ๊ตฌํ
ProcessA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Process A
// "Cat"์ด๋ผ๋ ์ด๋ฆ์ ์๋ก์ด ๋ฉ๋ชจ๋ฆฌ ๋งคํ๋ ํ์ผ์ ์์ฑํ๊ณ , ์ฉ๋์ 10000๋ฐ์ดํธ๋ก ์ค์ ํฉ๋๋ค.
using (var mmf = MemoryMappedFile.CreateNew("Cat", 10000))
{
// ๋ฉ๋ชจ๋ฆฌ ๋งต ํ์ผ์ ์ ์ฒด๋ฅผ ์ ๊ทผํ ์ ์๋ ๋ทฐ ์์ฑ
using (var accessor = mmf.CreateViewAccessor())
{
// ๋ฌธ์์ด ๋ฐ์ดํฐ๋ฅผ UTF8๋ก ์ธ์ฝ๋ฉํ์ฌ ๋ฐ์ดํธ ๋ฐฐ์ด๋ก ๋ณํ
string message = "HI Night Mo.";
byte[] bytes = Encoding.UTF8.GetBytes(message);
// ๋ทฐ๋ฅผ ํตํด ๋ฐ์ดํธ ๋ฐฐ์ด ๋ฐ์ดํฐ๋ฅผ ๋ฉ๋ชจ๋ฆฌ ๋งต ํ์ผ์ ์ฐ๊ธฐ
accessor.WriteArray(0, bytes, 0, bytes.Length);
Console.WriteLine("Message written to shared memory!");
}
}
ProcessB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Process B
// ๊ธฐ์กด์ ์์ฑ๋ ๋ฉ๋ชจ๋ฆฌ ๋งต ํ์ผ ์ด๊ธฐ
using (var mmf = MemoryMappedFile.OpenExisting("Cat"))
{
// ๋ฉ๋ชจ๋ฆฌ ๋งต ํ์ผ์ ์ ์ฒด๋ฅผ ์ ๊ทผํ ์ ์๋ ๋ทฐ ์์ฑ
using (var accessor = mmf.CreateViewAccessor())
{
// ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ๋ฐ์ดํธ ๋ฐฐ์ด ์์ฑ
byte[] bytes = new byte[10000];
// ๋ทฐ๋ฅผ ํตํด ๋ฉ๋ชจ๋ฆฌ ๋งต ํ์ผ์์ ๋ฐ์ดํฐ๋ฅผ ์ฝ์ด ๋ฐ์ดํธ ๋ฐฐ์ด์ ์ ์ฅ
accessor.ReadArray(0, bytes, 0, bytes.Length);
// ๋ฐ์ดํธ ๋ฐฐ์ด์ UTF8 ๋ฌธ์์ด๋ก ๋ณํ
string message = Encoding.UTF8.GetString(bytes).TrimEnd('\0');
Console.WriteLine("Message read from shared memory: " + message);
}
}
๊ฒฐ๊ณผ
๊ฐ๋จํ ์์ ๋ฅผ ํตํด์ Shared Memory๋ฅผ ๊ตฌํํด ๋ณด์๋ค.
This post is licensed under CC BY 4.0 by the author.
