1. [C#] 가비지 컬렉션(Garbage Collection)

개요)
C#은 CLR(Common Language Runtime)에 의해 코드가 실행되고 관리된다.
CLR에서 가비지 컬렉터(Garbage Collector)는 자동 메모리 관리자 역할을 한다. 애플리케이션에서 메모리 할당 및 해제를 자동으로 관리한다.

장점)
개발자가 수동으로 메모리를 관리할 일이 줄어든다. -> 개발 능률 Up
관리되는 힙(managed heap)에 메모리 할당이 효율적으로 이루어진다.
객체가 다른 객체에 할당된 메모리 자체에 사용할 수 없도록 하여 메모리 보안을 제공한다.

메모리 할당)
사용자에 의해 새 프로세스가 시작되면 런타임에서는 메모리에 인접한 주소 공간 영역을 예약한다.
이 예약된 주소 공간을 관리되는 힙(managed heap)이라고 한다.
관리되는 힙에서는 객체가 할당될 주소의 포인터를 관리한다.
모든 참조 형식(reference type)은 관리되는 힙에 할당된다.

과정)
애플리케이션에서 참조 형식을 처음 만드는 경우, 이 참조 형식에 대한 메모리는 관리되는 힙의 기본 주소로 할당된다.
애플리케이션이 다음 개체를 만들 때 런타음은 처음 만든 객체 바로 다음 주소 공간에 메모리를 할당한다.
이러한 방식을 반복하여 새 객체에 대한 메모리 공간을 계속 할당한다.
관리되는 힙은 관리되지 않는 힙(unmanaged heap)에서 할당하는 것보다 속도가 더 빠르다.
런타임에서 포인터에 값을 더하여 객체의 메모리를 할당하기 때문에, 스택에서 메모리를 할당하는 속도만큼 빠르다.
또한, 연속으로 할당된 새 객체는 인접한 주소를 통해 빠른 속도로 액세스할 수 있다.

메모리 해제)
가비지 컬렉터의 최적화 엔진은 수행 중인 할당에 따라 수집을 수행하기에 가장 적합한 시간을 결정한다.
애플리케이션에서 더 이상 사용되지 않는 객체에 대한 메모리를 해제한다.
애플리케이션의 루트를 검사하여 더 이상 사용되지 않는 개체를 결정한다.
애플리케이션 루트에는 다음이 포함된다.

정적 필드(static field)
스택 객체
CPU 레지스터 등

GC는 이 목록을 사용하여 루트를 통해 연결할 수 있는 모든 객체 그래프를 생성한다.
그래프에 연결되지 못한 객체는 가비지 컬렉터에서 가비지로 간주하고 할당을 해제한다.

가비지 컬렉션)
가비지 컬렉션은 다음 조건 중 하나가 충족될 경우 발생한다.
시스템 메모리 부족
관리되는 힙의 할당된 객체에 사용되는 메모리가 허용되는 최대치를 초과
GC.Collect 메서드 호출

세대)
관리되는 힙은 세대별로 나눠져 관리된다. 주로 0세대, 1세대, 2세대로 나뉜다.

0세대
새로 할당된 객체의 메모리 영역으로, 주로 이 세대에서 가비지 컬렉션이 자주 발생한다.
대부분의 객체는 0세대에서 정리되며 다음 세대까지 남아있지 않는다.
0세대가 가득 찼을 때 새 객체가 할당될 경우, 먼저 0세대 영역에서 검사가 이루어진다.

1세대
0세대 컬렉션을 수행한 후 살아남은 메모리를 압축하여 1세대로 승격한다.
컬렉션이 0세대에서 충분한 공간을 확보하지 못한 경우, 1세대와 2세대에서 수행한다.

2세대
가장 오랫동안 살아남은 객체들이 저장되는 공간이다.
대량 객체 힙(3세대)의 객체는 2세대에서도 컬렉션이 이루어진다.
관리되지 않는 리소스
대부분의 객체는 자동으로 관리되지만, 명시적인 정리가 필요한 관리되지 않는 리소스가 존재한다.

Dispose
이런 경우 IDisposable 인터페이스를 통해 Dispose 메서드를 재정의 하여 관련 작업을 수행한다.
public class MyClass : IDisposable
{
public void Dispose
    {
     //정리 로직 구현
    }
}
객체 사용을 마치면, 명시적으로 Dispose 메서드를 호출해야 한다.
Finalize
만일, 실수로 Dispose를 호출하지 않았을 경우를 대비하여 정리하는 방안도 마련할 수 있다.
객체가 가비지 컬렉션 될때 호출되는 Finalize를 재정의를 통해 수행하게 된다.
public class MyClass : IDisposable
{
public void Dispose {...}
    
    ~MyClass()
    {
     //정리 로직 구현
    }
}
다만 가비지 컬렉션 도중 특정 객체의 다른 작업이 수반되는 것이므로 성능 이슈가 발생한다.
이 방식은 되도록 사용하지 않는 것이 좋다.


1. 메모리 구조(C)

스택영역
우리는 이제껏 스택영역에 메모리를 할당해 왔습니다. 컴파일 시점에 결정되는 영역입니다.

힙 영역
이 영역의 메모리는 실행시점(Run Time)에 결정됩니다. 프로그래머에 의해서요. 이 영역을 힙영역이라고 합니다.

데이터 영역
이 영역의 메모리는 정적변수, 전역변수, 구조체 등 함수 외부에서 선언되는 변수들이 이 메모리에 할당됩니다.

코드 영역
코드영역에는 프로그램의 실행 명령어들이 존재합니다.

우리가 이번에 주목해야할 영역은 힙영역입니다. 위의 코드를 정상적이게 동작시키기 위해서는요.
그 목적을 달성하기 위해서 나온 함수가 바로 malloc함수입니다. malloc함수는 stdlib헤더에 선언되어 있으며 malloc함수를 사용하기 위해서는 stdlib.h를 include해야합니다.

void *malloc(size_t size)

이 함수는 size만큼의 메모리를 힙영역에 할당합니다. 어떤 자료형일지 모르니 반환형 데이터는 void포인터입니다. 
하지만 그냥 메모리만 할당하고 해제하지 않으면 메모리가 누출됩니다. 우리는 메모리를 이제 쓰지 않을 경우(거의 함수 반환 직전)에 free함수를 써서 메모리를 해제해야합니다.

void free(void *ptr)

1. 프로세스 리스트 확인 : tasklist
1) 설명 : 프로세스 리스트를 보여준다
2) 입력 구조 : TASKLIST [/S 시스템 [/U 사용자 이름 [/P [암호]]]] [/M [모듈] | /SVC | /V] [/FI 필터] [/FO 형식] [/NH]
3) 기본 구성 : 프로세스 명, pid, 세션명 등을 보여준다

2. 프로세스 kill : taskkill
설명 : 개발을 진행하거나 하다보면 여기저기 튀어나오는 좀비들때문에 여간 귀찮은것이 아니다.
          그럴때 프로세스를 죽일수 있는 명령어가 taskkill 이다
2) 기본 구성 : TASKKILL[/S시스템[/U사용자이름[/P[암호]]]] { [/FI 필터] [/PID 프로세스 id | /IM 이미지 이름] } [/T] [/F]
3) 주요 옵션
a. /PID 프로세스 ID : 특정 프로세스ID의 프로세스 종료하기
    예시 : taskkill /PID 21500 -> 21500 PID를 가지는 프로세스 종료해라
b. /IM 프로세스명 : 특정 이름을 가지는 프로세스 종료(와일드카드(*) 사용가능)
    예시 : taskkill /IM java* -> java로 시작하는 이름을 가진 프로세스 종료해라
c. /T : 지정된 프로세스와 그 자식 프로세스 까지 종료
예시 : taskkill /T /PID 21303 -> PID가 21303인 프로세스와 그 자식 프로세스 까지 종료

3. WMIC 명령어를 통한 부모 프로세스 찾기

wmic를 통해 보고싶은것만 찾아보자
   -> wmic process where 항목="항목값" get 파라미터1, 파라미터2, 파라미터3
   -> 프로세스 항목의 값이 "항목값인" 프로세스의 파라미터1, 파라미터2, 파라미터3 정보를 표시해준다.
예시) wmic process where name="chrome.exe" get processid, parentprocessid, commandline
       -> 프로세스명이 chrome.exe인 프로세스의 pid, ppid, commandline을 볼수 있다.

 


C:\Users>tasklist

이미지 이름                    PID 세션 이름              세션#  메모리 사용
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0          8 K
System                           4 Services                   0      1,164 K
Secure System                   56 Services                   0     22,768 K
Registry                       112 Services                   0     23,268 K
smss.exe                       396 Services                   0        956 K
csrss.exe                      568 Services                   0      3,892 K
wininit.exe                    668 Services                   0      4,140 K
services.exe                   892 Services                   0      7,948 K
LsaIso.exe                     900 Services                   0      3,484 K
lsass.exe                      920 Services                   0     12,788 K
svchost.exe                    356 Services                   0     18,748 K
fontdrvhost.exe                520 Services                   0      2,028 K
svchost.exe                    980 Services                   0     12,752 K
svchost.exe                   1068 Services                   0      6,900 K
svchost.exe                   1228 Services                   0      7,408 K
svchost.exe                   1240 Services                   0      6,648 K
svchost.exe                   1288 Services                   0      3,824 K
svchost.exe                   1404 Services                   0      5,512 K
svchost.exe                   1412 Services                   0      6,232 K
svchost.exe                   1476 Services                   0     14,064 K
svchost.exe                   1508 Services                   0     10,360 K
svchost.exe                   1568 Services                   0      4,260 K
svchost.exe                   1596 Services                   0      6,448 K
svchost.exe                   1604 Services                   0      5,120 K
svchost.exe                   1652 Services                   0      5,432 K
svchost.exe                   1704 Services                   0      4,872 K
svchost.exe                   1736 Services                   0      6,824 K
svchost.exe                   1916 Services                   0      7,768 K
WUDFHost.exe                  1940 Services                   0      4,496 K
svchost.exe                   2000 Services                   0      6,024 K
svchost.exe                   2008 Services                   0      4,196 K
svchost.exe                   2016 Services                   0      6,968 K
svchost.exe                   2112 Services                   0      7,512 K
svchost.exe                   2140 Services                   0      4,760 K
Memory Compression            2148 Services                   0    209,304 K
igfxCUIService.exe            2188 Services                   0      4,996 K
svchost.exe                   2196 Services                   0      4,376 K
svchost.exe                   2256 Services                   0      4,352 K
svchost.exe                   2272 Services                   0      4,140 K
svchost.exe                   2344 Services                   0      4,816 K
svchost.exe                   2464 Services                   0      4,568 K
svchost.exe                   2536 Services                   0      5,204 K
svchost.exe                   2564 Services                   0      5,280 K
svchost.exe                   2576 Services                   0      5,456 K
svchost.exe                   2708 Services                   0      6,068 K
svchost.exe                   2780 Services                   0      4,116 K
svchost.exe                   2864 Services                   0     11,904 K
svchost.exe                   2912 Services                   0      5,008 K
svchost.exe                   3016 Services                   0      4,668 K
svchost.exe                   3024 Services                   0      5,256 K
svchost.exe                   2948 Services                   0      4,376 K
svchost.exe                   3176 Services                   0      4,328 K
svchost.exe                   3212 Services                   0      8,216 K
svchost.exe                   3252 Services                   0      6,152 K
spoolsv.exe                   3340 Services                   0      5,708 K
svchost.exe                   3380 Services                   0      3,972 K
svchost.exe                   3476 Services                   0     14,992 K
svchost.exe                   3484 Services                   0      5,884 K
svchost.exe                   3492 Services                   0     20,832 K
eausvc.exe                    3500 Services                   0      1,720 K
ObCrossEXService.exe          3508 Services                   0      2,380 K
AnySign4PCLauncher.exe        3520 Services                   0      9,612 K
IniClientSvc_x64.exe          3532 Services                   0      5,548 K
kpmsvc.exe                    3544 Services                   0      1,736 K
macourtsafersvc.exe           3576 Services                   0      2,468 K
svchost.exe                   3600 Services                   0     23,728 K
svchost.exe                   3676 Services                   0      6,176 K
nossvc.exe                    3684 Services                   0      1,384 K
runSW.exe                     3704 Services                   0      2,860 K
ASDSvc.exe                    3720 Services                   0     11,492 K
svchost.exe                   3728 Services                   0      4,060 K
svchost.exe                   3740 Services                   0      4,516 K
TENXW_SVR.exe                 3804 Services                   0      4,160 K
MsMpEng.exe                   3868 Services                   0    218,900 K
svchost.exe                   3892 Services                   0      3,912 K
svchost.exe                   3916 Services                   0      8,240 K
wpmsvc.exe                    3936 Services                   0      6,412 K
svchost.exe                   3996 Services                   0      5,548 K
svchost.exe                   4104 Services                   0      3,916 K
svchost.exe                   4352 Services                   0      4,048 K
svchost.exe                   4480 Services                   0      6,004 K
wlanext.exe                   4612 Services                   0      4,608 K
conhost.exe                   4632 Services                   0      3,328 K
NisSrv.exe                    5512 Services                   0      6,948 K
svchost.exe                   5876 Services                   0     13,572 K
PresentationFontCache.exe     6736 Services                   0      4,220 K
svchost.exe                   6852 Services                   0     12,852 K
svchost.exe                   7044 Services                   0      4,600 K
svchost.exe                   7088 Services                   0      6,744 K
svchost.exe                   7428 Services                   0      4,784 K
svchost.exe                   7632 Services                   0      8,096 K
svchost.exe                   7960 Services                   0      5,472 K
svchost.exe                   9388 Services                   0     10,012 K
svchost.exe                   9544 Services                   0     28,188 K
SearchIndexer.exe             9860 Services                   0     20,920 K
svchost.exe                   1332 Services                   0      8,232 K
svchost.exe                   3412 Services                   0      8,052 K
GoogleCrashHandler.exe       11268 Services                   0        752 K
GoogleCrashHandler64.exe     11276 Services                   0        632 K
svchost.exe                  12040 Services                   0      8,956 K
svchost.exe                  12212 Services                   0      6,048 K
SecurityHealthService.exe    12096 Services                   0     12,520 K
svchost.exe                   9812 Services                   0      5,148 K
SgrmBroker.exe                8676 Services                   0      7,504 K
svchost.exe                  11304 Services                   0      8,516 K
svchost.exe                   7844 Services                   0      4,596 K
csrss.exe                     3140 Console                    2      4,260 K
winlogon.exe                 14184 Console                    2      5,940 K
fontdrvhost.exe              12684 Console                    2      4,444 K
dwm.exe                      13324 Console                    2     42,940 K
MoUsoCoreWorker.exe           3908 Services                   0     18,648 K
TEWebP.exe                    9676 Console                    2      4,740 K
TEWebP64.exe                  9712 Console                    2      6,660 K
svchost.exe                   9120 Services                   0      7,272 K
svchost.exe                   4620 Services                   0      4,216 K
SwUSB.exe                    12296 Console                    2      5,272 K
AnySign4PC.exe               12552 Console                    2      8,784 K
kpmcnt.exe                    8272 Console                    2      2,756 K
sihost.exe                    6000 Console                    2     18,520 K
svchost.exe                   4492 Console                    2     16,296 K
svchost.exe                   9336 Console                    2     17,144 K
taskhostw.exe                13520 Console                    2      9,328 K
igfxEM.exe                    4316 Console                    2      8,168 K
igfxHK.exe                    7564 Console                    2      6,936 K
igfxTray.exe                  2632 Console                    2      7,988 K
INISAFEAdminUtil.exe         10336 Console                    2      2,488 K
ctfmon.exe                   10724 Console                    2      9,280 K
explorer.exe                 10788 Console                    2     70,700 K
nosstarter.npe                6708 Console                    2     11,500 K
svchost.exe                   8216 Console                    2      8,980 K
macourtsafer.exe             12112 Console                    2      2,540 K
CrossEXService.exe           10852 Console                    2      2,708 K
msedge.exe                    5048 Console                    2     99,368 K
msedge.exe                   13576 Console                    2      5,352 K
TEWeb.exe                    13432 Console                    2      3,868 K
msedge.exe                   10044 Console                    2    118,148 K
msedge.exe                   13420 Console                    2     25,536 K
msedge.exe                   11516 Console                    2      6,620 K
TEWeb64.exe                  11128 Console                    2      6,820 K
delfino.exe                  11952 Console                    2      6,644 K
INISAFECrossWebEXSvc.exe     10216 Console                    2      7,412 K
veraport-x64.exe             13136 Console                    2      8,596 K
StartMenuExperienceHost.e    12808 Console                    2     25,048 K
StSess.exe                   13888 Console                    2      7,072 K
RuntimeBroker.exe            10136 Console                    2      9,900 K
SearchApp.exe                 6424 Console                    2    118,648 K
RuntimeBroker.exe            11444 Console                    2      9,624 K
SkypeBackgroundHost.exe      14464 Console                    2      5,184 K
SkypeApp.exe                 14496 Console                    2     95,716 K
LockApp.exe                  14644 Console                    2      7,148 K
RuntimeBroker.exe            14808 Console                    2      9,008 K
StSess32.exe                 15156 Console                    2      2,788 K
RuntimeBroker.exe            11080 Console                    2      7,264 K
RuntimeBroker.exe            15432 Console                    2      8,796 K
SecurityHealthSystray.exe    15560 Console                    2      6,976 K
OneDrive.exe                 16048 Console                    2     21,184 K
ShellExperienceHost.exe      16260 Console                    2     23,260 K
jusched.exe                  16348 Console                    2      3,396 K
RuntimeBroker.exe            16288 Console                    2      9,236 K
SkypeBridge.exe              16672 Console                    2     22,336 K
TextInputHost.exe            17316 Console                    2     12,560 K
dllhost.exe                   8900 Console                    2      6,124 K
KakaoTalk.exe                16528 Console                    2    116,472 K
msedge.exe                   16804 Console                    2    180,808 K
dllhost.exe                  17128 Console                    2      5,492 K
svchost.exe                   9400 Console                    2      6,012 K
svchost.exe                  11156 Services                   0      6,232 K
ApplicationFrameHost.exe      3572 Console                    2      8,028 K
jucheck.exe                  14308 Console                    2      4,544 K
UserOOBEBroker.exe           12860 Console                    2      7,132 K
msedge.exe                   15580 Console                    2    154,940 K
msedge.exe                   16304 Console                    2     61,860 K
msedge.exe                    9504 Console                    2     11,652 K
chrome.exe                   15596 Console                    2     86,588 K
chrome.exe                    9084 Console                    2      5,744 K
chrome.exe                    9296 Console                    2     67,316 K
chrome.exe                    1744 Console                    2     17,320 K
chrome.exe                    9220 Console                    2      7,936 K
chrome.exe                   10392 Console                    2     48,676 K
chrome.exe                   12024 Console                    2     12,752 K
cmd.exe                       9592 Console                    2      3,928 K
conhost.exe                  15308 Console                    2     19,360 K
svchost.exe                  12504 Services                   0     10,836 K
svchost.exe                  16032 Services                   0      7,472 K
Microsoft.Photos.exe         15568 Console                    2     15,896 K
svchost.exe                  17512 Services                   0      8,492 K
svchost.exe                  18828 Services                   0      6,504 K
RuntimeBroker.exe            18480 Console                    2     14,728 K
VSSVC.exe                     9000 Services                   0      9,968 K
svchost.exe                  17696 Services                   0      9,140 K
WmiPrvSE.exe                 18916 Services                   0      9,452 K
svchost.exe                   6240 Services                   0     12,596 K
backgroundTaskHost.exe       17640 Console                    2     27,112 K
RuntimeBroker.exe            18476 Console                    2     21,824 K
TrustedInstaller.exe         11364 Services                   0      7,856 K
svchost.exe                  10780 Services                   0      7,772 K
svchost.exe                  18036 Services                   0      8,288 K
smartscreen.exe               7556 Console                    2      9,196 K
svchost.exe                   8056 Services                   0      8,248 K
tasklist.exe                  2824 Console                    2      9,528 K
WmiPrvSE.exe                  6368 Services                   0      9,972 K

C:\Users>
C:\Users>wmic process where name="svchost.exe" get processid, parentprocessid, commandline
CommandLine                                                            ParentProcessId  ProcessId
                                                                       892              356
                                                                       892              980
                                                                       892              1068
                                                                       892              1228
                                                                       892              1240
                                                                       892              1288
                                                                       892              1404
                                                                       892              1412
                                                                       892              1476
                                                                       892              1508
                                                                       892              1568
                                                                       892              1596
                                                                       892              1604
                                                                       892              1652
                                                                       892              1704
                                                                       892              1736
                                                                       892              1916
                                                                       892              2000
                                                                       892              2008
                                                                       892              2016
                                                                       892              2112
                                                                       892              2140
                                                                       892              2196
                                                                       892              2256
                                                                       892              2272
                                                                       892              2344
                                                                       892              2464
                                                                       892              2536
                                                                       892              2564
                                                                       892              2576
                                                                       892              2708
                                                                       892              2780
                                                                       892              2864
                                                                       892              2912
                                                                       892              3016
                                                                       892              3024
                                                                       892              2948
                                                                       892              3176
                                                                       892              3212
                                                                       892              3252
                                                                       892              3380
                                                                       892              3476
                                                                       892              3484
                                                                       892              3492
                                                                       892              3600
                                                                       892              3676
                                                                       892              3728
                                                                       892              3740
                                                                       892              3892
                                                                       892              3916
                                                                       892              3996
                                                                       892              4104
                                                                       892              4352
                                                                       892              4480
                                                                       892              5876
                                                                       892              6852
                                                                       892              7044
                                                                       892              7088
                                                                       892              7428
                                                                       892              7632
                                                                       892              7960
                                                                       892              9388
                                                                       892              9544
                                                                       892              1332
                                                                       892              3412
                                                                       892              12040
                                                                       892              12212
                                                                       892              9812
                                                                       892              11304
                                                                       892              7844
                                                                       892              9120
                                                                       892              4620
C:\Windows\system32\svchost.exe -k UnistackSvcGroup -s CDPUserSvc      892              4492
C:\Windows\system32\svchost.exe -k UnistackSvcGroup -s WpnUserService  892              9336
C:\Windows\system32\svchost.exe -k ClipboardSvcGroup -p -s cbdhsvc     892              8216
C:\Windows\system32\svchost.exe -k UnistackSvcGroup                    892              9400
                                                                       892              11156
                                                                       892              12504
                                                                       892              16032
                                                                       892              17512
                                                                       892              18828
                                                                       892              17696
                                                                       892              6240
                                                                       892              10780
                                                                       892              18036


C:\Users>
C:\Users>tasklist

이미지 이름                    PID 세션 이름              세션#  메모리 사용
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0          8 K
services.exe                   892 Services                   0      7,948 K
wininit.exe                    668 Services                   0      4,140 K


wmic process where name="services.exe" get processid, parentprocessid, commandline
C:\Users>wmic process where name="services.exe" get processid, parentprocessid, commandline
CommandLine  ParentProcessId  ProcessId
             668              892

wmic process where name="wininit.exe" get processid, parentprocessid, commandline
C:\Users>wmic process where name="wininit.exe" get processid, parentprocessid, commandline
CommandLine  ParentProcessId  ProcessId
             552              668

C:\Users>

C:\Users>wmic process where name="System Idle Process" get processid, parentprocessid, commandline
CommandLine  ParentProcessId  ProcessId
             0                0


C:\Users>



taskkill /T /PID 21303 -> PID가 21303인 프로세스와 그 자식 프로세스 까지 종료

taskkill /T /PID 0
C:\Windows\system32>taskkill /T /PID 0
오류: PID 56인 프로세스(PID 4인 자식 프로세스)를 종료할 수 없습니다.
원인: 액세스가 거부되었습니다.
오류: PID 112인 프로세스(PID 4인 자식 프로세스)를 종료할 수 없습니다.
원인: 액세스가 거부되었습니다.
오류: PID 396인 프로세스(PID 4인 자식 프로세스)를 종료할 수 없습니다.
원인: 이 프로세스는 중대한 시스템 프로세스입니다. Taskkill에서 이 프로세스를 종료할 수 없습니다.
오류: PID 2148인 프로세스(PID 4인 자식 프로세스)를 종료할 수 없습니다.
원인: 액세스가 거부되었습니다.
오류: PID 4인 프로세스(PID 0인 자식 프로세스)를 종료할 수 없습니다.
원인: 이 프로세스의 자식 프로세스가 하나 이상 실행되고 있습니다.
오류: PID 0인 프로세스(PID 0인 자식 프로세스)를 종료할 수 없습니다.
원인: 이 프로세스의 자식 프로세스가 하나 이상 실행되고 있습니다.

C:\Windows\system32>


# SetWindowLong 함수란 무엇인가,mmmm
# SetWindowLong 함수란 무엇인가,mmmm

 


SetWindowLong 
LONG WINAPI SetWindowLong(
_In_HWND hWnd,
_In_int nIndex,
_In_LONG dwNewLong
);

지정된 윈도우의 속성을 변경합니다. 이 함수로 지정된 기능을 32bit 값으로 메모리에 추가합니다.
이 함수는 SetWindowLongPtr 함수로 대체 되었습니다.32bit, 64bit와 호환됩니다. 사용법은 같습니다.
이 함수는 SetWindowPos함수를 호출할때까지 적용되지 않습니다.

hWnd
변경을 원하는 윈도우의 핸들

nIndex
어느 설정을 변경 할 것인지 정해진 상수로 넣어줍니다.
GWL_STYLE - 새로운 윈도우 스타일을 설정합니다.
GWL_EXSTYLE - 새로운 확장 윈도우 스타일을 설정합니다.
GWL_HINSTANCE - 새 응용 프로그램 인스턴스 핸들을 설정합니다.
GWL_ID - 하위 윈도우의 새 식별자를 설정합니다. 창은 최상위 창이 될수없습니다.
GWL_USERDATA - 창과 관련된 사용자 데이터를 설정합니다. 이 값은 창을 만든 응용프로그램에서 사용하기 위한 값입니다. 초기 값은 0입니다.
GWL_WNDPROC - 윈도우 프로시저의 새주소를 설정합니다. 창이 호출한 스레도와 동일한 프로세스에 속하지 않으면 이 값은 변경 할수 없습니다.


Ex)
public static extern Int32 GetWindowLong(IntPtr hWnd, Int32 Offset);
[DllImport("user32.dll")]
public static extern Int32 SetWindowLong(IntPtr hWnd, Int32 Offset, Int32 newLong);
[DllImport("user32.dll")]

WindowStyle myStyle = (WindowStyle)style;
myStyle = myStyle & ~WindowStyle.WS_SYSMENU;
style = SetWindowLong(childForm.Handle, GWL_STYLE, (int)myStyle);

#함수를 하나만 사용해서, 두개의 함수를 구현하는 방법(오버라이딩의 진화,ㅡ,ㅡㅡ)
#함수를 하나만 사용해서, 두개의 함수를 구현하는 방법(오버라이딩의 진화,ㅡ,ㅡㅡ)
#함수를 하나만 사용해서, 두개의 함수를 구현하는 방법(오버라이딩의 진화,ㅡ,ㅡㅡ)


using System;

class Program
{
    public static void Main(string[] args)
    {
        checkparameters nm = new checkparameters();
nm.run();

checkparametersdown nmm = new checkparametersdown();
nmm.run();
    }
}

//함수를 하나만 사용해서, 두개의 함수를 구현하는 방법
//함수를 하나만 사용해서, 두개의 함수를 구현하는 방법
class checkparameters
{
    void basefrm(string portno, string apmLiteRedismanager, string apmLiteRedismanagers = null )
    {
        Console.WriteLine(portno + "/" + apmLiteRedismanager + "/" + apmLiteRedismanagers);
    }
    public void run()
    {
        basefrm("1010", "1010");
basefrm("1010", "1010", "1010");
    }
}
class checkparametersdown
{
    void basefrm(string portno, string apmLiteRedismanager, string apmLiteRedismanagers)
    {
        Console.WriteLine(portno + "/" + apmLiteRedismanager + "/" + apmLiteRedismanagers);
    }
    void basefrm(string portno, string apmLiteRedismanager)
    {
        Console.WriteLine(portno + "/" + apmLiteRedismanager);
    }
    public void run()
    {
        basefrm("1010", "1010");
basefrm("1010", "1010", "1010");
    }
}



[Git] push 명령어로 local 변경 사항 원격 저장소에 반영하기
[Git] push 명령어로 local 변경 사항 원격 저장소에 반영하기
[Git] push 명령어로 local 변경 사항 원격 저장소에 반영하기
[Git] push 명령어로 local 변경 사항 원격 저장소에 반영하기
[Git] push 명령어로 local 변경 사항 원격 저장소에 반영하기







아래는 해당 프로젝트 소스디렉토리로 이동해서 수정된 부분을 반영하는 방법이다.

>cd ~/source/repository/Final/
>git branch -M BRANCH_PROJECT_NAME
>git add .
>git commit -m "query 2024.01.25 history commit"
>git push -u origin BRANCH_PROJECT_NAME


- git commit과 push의 차이점 이해하기
- git commit과 push의 차이점 이해하기
- git commit과 push의 차이점 이해하기

그렇다면 git commit과 push의 차이는 뭘까?
그렇다면 git commit과 push의 차이는 뭘까?
그렇다면 git commit과 push의 차이는 뭘까?

git commit만으로는 왜 원격 저장소에 반영이 안될까?
git commit만으로는 왜 원격 저장소에 반영이 안될까?
git commit만으로는 왜 원격 저장소에 반영이 안될까?

우리가 데이터를 변경한 후 commit을 하면 그 내역은 로컬 저장소에 반영이 된다.
우리가 데이터를 변경한 후 commit을 하면 그 내역은 로컬 저장소에 반영이 된다.
우리가 데이터를 변경한 후 commit을 하면 그 내역은 로컬 저장소에 반영이 된다.
즉, 내 pc 내의 저장소에만 반영이 된 것이다.
즉, 내 pc 내의 저장소에만 반영이 된 것이다.
즉, 내 pc 내의 저장소에만 반영이 된 것이다.

로컬저장소에 반영된 변경 사항을 원격에도 반영하기 위한 도구가 push다.
로컬저장소에 반영된 변경 사항을 원격에도 반영하기 위한 도구가 push다.
로컬저장소에 반영된 변경 사항을 원격에도 반영하기 위한 도구가 push다.

commit한 내역을 push하게 되면, 이제 원격 저장소에도 그 내역이 업데이트 되는 것이다.
commit한 내역을 push하게 되면, 이제 원격 저장소에도 그 내역이 업데이트 되는 것이다.
commit한 내역을 push하게 되면, 이제 원격 저장소에도 그 내역이 업데이트 되는 것이다.

따라서, commit은 내 pc 내의 작업이 때문에 크게 위험하지 않다.
따라서, commit은 내 pc 내의 작업이 때문에 크게 위험하지 않다.
따라서, commit은 내 pc 내의 작업이 때문에 크게 위험하지 않다.

하지만 push는 원격 저장소, 즉 공동으로 작업하는 프로젝트에 (개인 프로젝트일 수도 있지만)
하지만 push는 원격 저장소, 즉 공동으로 작업하는 프로젝트에 (개인 프로젝트일 수도 있지만)
하지만 push는 원격 저장소, 즉 공동으로 작업하는 프로젝트에 (개인 프로젝트일 수도 있지만)

그 내역이 반영되는 것이기 때문에 신중하게 해야한다.
그 내역이 반영되는 것이기 때문에 신중하게 해야한다.
그 내역이 반영되는 것이기 때문에 신중하게 해야한다.





 

"파일"이라는 한글을 여러타입으로 저장후에 c언어에서 읽어서 출력해보기
"파일"이라는 한글을 여러타입으로 저장후에 c언어에서 읽어서 출력해보기
"파일"이라는 한글을 여러타입으로 저장후에 c언어에서 읽어서 출력해보기


c언어에서 언어셋을 다루는일은 어려운일이다. 특히 한글을 다루는 일은 더더욱 그렇다.
아래는 여러가지 방식으로 저장되어진 "파일"이라는 한글을 바이트단위로 출력해본다.

 

 

#include <stdio.h>
#include <string.h>
 
int main(int argc, char *argv[])
{
    int kk;
    char tmp[1024];
    FILE *fp = NULL;

    if(argc != 2) return(-1);

    if(( fp = fopen(argv[1], "rt")) == NULL) return(-1);

    memset(tmp, 0x00, sizeof(tmp));

    while(1)
    {
        memset(tmp, 0x00, sizeof(tmp));
        if(fgets(tmp, sizeof(tmp), fp) == NULL) break;

        for(kk=0; kk<sizeof(tmp); kk++)
        {
            if(tmp[kk]==0x00) break;
            printf("[%d],", tmp[kk]);
        }
        printf("\n");
        printf("%s", tmp);
        printf("\n");
    }

    if(fp != NULL) fclose(fp);
    return(0);
}

한글꺠짐.언어설정) SAMSUNG.NOTE

한글안꺠짐.언어설정) DELL

sinfo@sinfo:/data/exture_3_0/20221026$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
sinfo@sinfo:/data/exture_3_0/20221026$

ftp 설치

>apt-get install vsftpd
>vim /etc/vsftpd.conf

chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list
allow_writeable_chroot=YES
write enable=YES

vsftpd.chroot_list 파일에 있는 “특정 사용자”에 대해서만 접근을 할 수 있도록 해주는 내용입니다.
해당 파일은 없기 때문에 파일을 생성해 원하시는 계정명을 1줄씩 입력하시면 됩니다.


service vsftpd restart
ufw allow 21/tcp

> Ubuntu 20.04 환경에서 Telnet을 설치하는 방법

$apt-get install xinetd telnetd
$vi /etc/xinetd.d/telnet

service telnet
{
disable = no
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd
log_on_failure += USERID
}

$ sudo systemctl restart xinetd
$ sudo systemctl enable xinetd
$ sudo ufw allow 23/tcp



>>1.
Ubuntu의 파일 시스템은 Linux 운영 체제에서 사용되는 파일 및 디렉토리 구조를 나타냅니다. Ubuntu는 일반적으로 ext4 파일 시스템을 사용하지만 다른 파일 시스템도 선택할 수 있습니다. 여기에는 주요 디렉토리와 파일 시스템의 일반적인 구성 요소가 포함됩니다:

/ (루트 디렉토리): 모든 파일 시스템의 시작점입니다. 모든 파일 및 디렉토리는 여기에 포함됩니다.
/bin: 바이너리 실행 파일이 저장되는 디렉토리입니다. 일반적으로 시스템 부팅시 필요한 핵심 명령어가 여기에 있습니다.
/boot: 부트로더 및 커널 이미지 파일이 저장되는 디렉토리입니다.
/dev: 장치 파일이 위치하는 디렉토리입니다. 시스템에서 사용되는 각종 하드웨어 및 장치들이 여기에 포함됩니다.
/etc: 시스템 구성 파일이 저장되는 디렉토리입니다. 네트워크, 소프트웨어 설정 등이 여기에 있습니다.
/home: 사용자 홈 디렉토리가 있는 곳입니다. 각 사용자의 개인 파일과 설정이 이 디렉토리에 저장됩니다.
/lib: 라이브러리 파일이 위치하는 디렉토리입니다. 실행 파일에서 라이브러리를 참조할 때 사용됩니다.
/media: 외부 매체(USB 드라이브, CD-ROM 등)를 마운트하는 디렉토리입니다.
/mnt: 일시적으로 파일 시스템을 마운트하는 디렉토리입니다.
/opt: 선택적 응용 프로그램이 설치되는 디렉토리입니다.
/proc: 시스템 프로세스 정보가 포함된 가상 파일 시스템입니다.
/root: 시스템 관리자(root)의 홈 디렉토리입니다.
/sbin: 시스템 관리용 바이너리가 저장되는 디렉토리입니다. 주로 시스템 관리 작업에 사용됩니다.
/srv: 서비스 관련 데이터가 저장되는 디렉토리입니다.
/sys: 시스템 관련 정보가 포함된 가상 파일 시스템입니다.
/tmp: 임시 파일이 저장되는 디렉토리입니다. 일반적으로 시스템 재부팅시 삭제됩니다.
/usr: 시스템 사용자용 응용 프로그램 및 데이터가 있는 디렉토리입니다.
/var: 변수 데이터가 있는 디렉토리입니다. 주로 로그 파일, 프로세스 파일 등이 여기에 저장됩니다.
이러한 디렉토리 및 파일 시스템 구조는 Ubuntu 및 기타 Linux 배포판에서 일반적으로 사용됩니다.



>> 2.
900기가 가준 ubuntu file system 적정용량

900GB의 저장 공간을 가진 시스템에서 Ubuntu를 설치할 때 적절한 파일 시스템 용량은 여러 요소에 따라 달라집니다. 일반적으로 다음을 고려할 수 있습니다:
루트 파일 시스템 (/): 운영 체제와 시스템 소프트웨어를 포함하는 곳입니다. 일반적으로 20GB에서 50GB 정도의 공간을 할당하는 것이 권장됩니다.
홈 디렉토리 (/home): 사용자 파일과 데이터가 저장되는 곳입니다. 여기에 할당되는 공간은 사용자의 파일 크기와 데이터 관리 요구 사항에 따라 달라집니다. 일반적으로 사용자당 몇 십 기가바이트에서 수백 기가바이트의 공간을 고려할 수 있습니다.
기타 디렉토리 및 파티션: 시스템에 따라 추가적인 디렉토리나 파티션이 필요할 수 있습니다. 예를 들어, 데이터베이스 서버, 웹 서버, 파일 서버 등의 특정 응용 프로그램을 실행하는 경우 해당 데이터가 저장될 디렉토리나 파티션에 대한 공간을 고려해야 합니다.
900GB의 저장 공간을 가진 시스템에서는 다음과 같은 공간 할당을 고려할 수 있습니다:

루트 파일 시스템 (/): 50GB
홈 디렉토리 (/home): 나머지 공간 (약 850GB)
이렇게 할당된 공간을 기준으로 시스템을 설치하면 운영 체제 및 사용자 데이터를 관리하는 데 충분한 여유 공간을 확보할 수 있습니다. 필요에 따라 이러한 용량을 조정하거나 추가 디렉토리를 생성하여 사용할 수 있습니다.

>> 3.
900GB의 용량을 위한 파일 시스템 용량 배분의 경우, 각 디렉토리의 예상 사용량과 시스템 요구 사항을 고려하여 적정한 용량을 할당할 수 있습니다. 다음은 일반적인 용량 할당 예시입니다:

/ (루트 디렉토리): 50GB
/bin: 5GB
/boot: 10GB
/dev: 5GB
/etc: 10GB
/home: 200GB (사용자 파일 및 설정에 대한 공간)
/lib: 5GB
/media: 10GB
/mnt: 10GB
/opt: 20GB
/proc: 1GB
/root: 10GB
/sbin: 5GB
/srv: 20GB
/sys: 1GB
/tmp: 20GB
/usr: 200GB (시스템 응용 프로그램 및 데이터)
/var: 200GB (로그 및 변수 데이터)
이렇게 할당된 용량은 다양한 디렉토리 및 시스템 요구 사항을 고려하여 조정될 수 있습니다. 특히, 사용자 파일 저장 공간 (/home) 및 시스템 로그 및 데이터 저장 공간 (/var)의 할당은 실제 사용량 및 시스템 용도에 따라 조정될 수 있습니다.




# Windows Console에 Sin,Cos 그래프 표시

 

 

 



using System;

class Program
{
    public static void Main(string[] args)
    {
        CHKNM nmm = new CHKNM();
nmm.RUN();
    }
}
class CHKNM
{
    //Console Width, Heigth
    int width = 0;
    int height = 0;

    //Math.Cos,Math.Sin's Value to mapping Console Screen Size
    double mapx = 0.0;
    double mapy = 0.0;

    int toggle = 0;
    int nextxpos = 0;

    int end_degree_value = 360 * 2;

    public void RUN()
    {
width  = Console.WindowWidth;
        height = Console.WindowHeight;

        //Dynamic array index possible
int[,] screenposition = new int[width,height];

for(int ii=0; ii<height; ii++)
for(int kk=0; kk<width; kk++)
{
    screenposition[kk,ii]=0;
}

        for(int degree = 1; degree < end_degree_value; degree++)
{
    double radian = Math.PI * degree / 180.0;
    double funcy = Math.Cos(radian) + 1.0;

    mapy = height * 0.99 / 4.0;
    mapx = Convert.ToDouble(width) / Convert.ToDouble(end_degree_value);

    int ypos = Convert.ToInt32(funcy * mapy);
    int xpos = Convert.ToInt32(degree * mapx);

    if(ypos == height) continue;
    if(xpos == width) continue;

            if(toggle == 0)
    {
        toggle = 100;
nextxpos = xpos;
screenposition[xpos,ypos]=1;
    }
    else
    {
        if(nextxpos == xpos) continue;
else
{
    screenposition[xpos,ypos]=1;
    nextxpos = xpos;
}
    }
}
#if(true)
        string screenTxt = "";
for(int ii=0; ii<height/2; ii++)
{
    for(int kk=0; kk<width; kk++)
    {
        if(screenposition[kk,ii] == 1) screenTxt += "*";
else screenTxt += " ";
    }
    screenTxt += "\n";
}
Console.WriteLine(screenTxt);
#endif
    }
}









 

 

1. 1단계 - Visual Studio 부트스트래퍼 다운로드

Download the correct bootstrapper for the version and edition of Visual Studio you want

Create a network-based installation - Visual Studio (Windows) | Microsoft Learn

Edition                                        Bootstrapper
Visual Studio 2022 Enterprise    vs_enterprise.exe
Visual Studio 2022 Professional vs_professional.exe
Visual Studio 2022 Community   vs_community.exe
Visual Studio 2022 Build Tools    vs_buildtools.exe


2. 2단계 - 로컬 레이아웃 만들기
vs_enterprise.exe --layout c:\localVSlayout



3. 3단계
vs_setup.exe --config d:\takeover\vsconfig\myconfig.vsconfig

 

Create a network-based installation - Visual Studio (Windows)

Create a private network install point to deploy Visual Studio to support enterprise users with limited permissions or client machines with limited internet access.

learn.microsoft.com

 

4. 4단계

Microsoft Visual Studio Installer Projects 2022 확장프로그램 download

InstallerProjects2022.vsix 를 클릭해서 진행하면 된다.(자동설치)

Microsoft Visual Studio Installer Projects 2022 - Visual Studio Marketplace

 

Microsoft Visual Studio Installer Projects 2022 - Visual Studio Marketplace

Extension for Visual Studio - This official Microsoft extension provides support for Visual Studio Installer Projects in Visual Studio 2022.

marketplace.visualstudio.com




# visual studio offline 2019->2022 설치

# visual studio offline 2019가 이미 설치되어져 있다.
# visual studio offline 2022를 동시에 설치한다.

- 현재 장비에 인터넷은 되지 않는다. 통합설치는 불가능하고, 개별설치로 2019를 설치해서 사용중이다.
- 어찌 어찌 visual studio offline 2019 버젼을 설치해서 소스코드를 빌드해서 사용중이다.
- 이제 visual studio offline 2022버젼을 설치해야 한다. 물론 이것도 개별설치로 진행해야 할것이다. 통합설치는 불가능.



    - (참고문헌의 예)
    - (99.9) Visual Studio(2019) 설치 관리자를 엽니다. 제품 카드에서 기타 단추를 선택한 후 구성 내보내기를 선택합니다.

- Visual studio offline 2022버젼 binary 폴더로 이동한다.
- (99.9)의 내용을 d:\tmp\memo\myconfig.vsconfig로 저장한다.
- 아래의 shell을 실행한다.
- vs_setup.exe --config d:\tmp\memo\myconfig.vsconfig
- 실행결과 (?)
- InstallerProjects2022.visx 확장프로그램 더블클릭시에, 자동실행
- Visual Studio 2022에 확장 이식가능.
- Visual Studio 2019는 InstallerProjects.visx로 해야한다.
- 실행결과 (?)

호환적인부분에서 문제점이 발견되어진다. 해결방법은(?)


 

Visual studio 2019 Installer 내보내기결과)

{
  "version": "1.0",
  "components": [
    "Microsoft.VisualStudio.Component.CoreEditor",
    "Microsoft.VisualStudio.Workload.CoreEditor",
    "Microsoft.VisualStudio.Component.NuGet",
    "Microsoft.VisualStudio.Component.Roslyn.Compiler",
    "Microsoft.VisualStudio.Component.Roslyn.LanguageServices",
    "Microsoft.Net.Component.4.8.SDK",
    "Microsoft.Net.Component.4.7.2.TargetingPack",
    "Microsoft.Net.ComponentGroup.DevelopmentPrerequisites",
    "Microsoft.Component.MSBuild",
    "Microsoft.VisualStudio.Component.TextTemplating",
    "Microsoft.Net.Component.4.TargetingPack",   -> 2022에 적용되지 않음(?)
    "Microsoft.Net.Component.4.6.TargetingPack",
    "Microsoft.VisualStudio.Component.DiagnosticTools",
    "Microsoft.VisualStudio.Component.AppInsights.Tools",
    "Microsoft.VisualStudio.Component.IntelliCode",
    "Microsoft.Net.Component.4.8.TargetingPack",
    "Microsoft.VisualStudio.Component.VSSDK",
    "Microsoft.VisualStudio.ComponentGroup.VisualStudioExtension.Prerequisites",
    "Microsoft.VisualStudio.Component.DslTools",
    "Microsoft.Component.CodeAnalysis.SDK",
    "Microsoft.VisualStudio.Workload.VisualStudioExtension",
    "Microsoft.Component.ClickOnce"
  ]
}

 

Windows Form 실행시에 Message 순서출력
Windows Form 실행시에 Message 순서출력, Windows Form 실행시에 Message 순서출력

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private IntPtr tailHandle = IntPtr.Zero;
        int index = 0;
        public Form1()
        {
            InitializeComponent();

            //this.Visible=false;
        }
        private void SendToTail(int index, string data)
        {
            tailHandle = APMApiPublic.FindWindow(null, "DEBUGDEBUGDEBUG");
            if (tailHandle != IntPtr.Zero && data.Length > 0 && APMApiPublic.IsWindow(tailHandle))
            {
                try
                {
                    byte[] dataByte = Encoding.UTF8.GetBytes(data);

                    APMApiPublic.COPYDATASTRUCT copyData = new APMApiPublic.COPYDATASTRUCT();
                    copyData.dwData = (IntPtr)0;
                    copyData.cbData = dataByte.Length;
                    copyData.lpData = Marshal.AllocHGlobal(dataByte.Length);
                    Marshal.Copy(dataByte, 0, copyData.lpData, dataByte.Length);

                    IntPtr sendData = Marshal.AllocHGlobal(Marshal.SizeOf(copyData));
                    Marshal.StructureToPtr(copyData, sendData, true);

                    IntPtr _result = APMApiPublic.SendMessage(tailHandle, APMApiPublic.WM_COPYDATA, (IntPtr)index, sendData);

                    Marshal.FreeHGlobal(copyData.lpData);
                    Marshal.FreeHGlobal(sendData);
                }
                catch (Exception exp)
                {
                    //MessageBox.Show(exp.Message);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SendToTail(1, "(Form1_Load)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            SendToTail(1, "(Form1_Shown)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }

        private void Form1_Enter(object sender, EventArgs e)
        {
            SendToTail(1, "(Form1_Enter)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }

        private void Form1_ForeColorChanged(object sender, EventArgs e)
        {
            SendToTail(1, "(Form1_ForeColorChanged)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            SendToTail(1, "(Form1_FormClosed)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            SendToTail(1, "(Form1_Activated)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            SendToTail(1, "(Form1_Paint)()()()()()[INDEX]:" + index.ToString("0000000"));
            index++;
        }
    }
}

 

 

 

현재 로칼 컴퓨터의 아이피 알아내기





using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Diagnostics;
using System;
using System.Linq;
using System.Net;

class Program
{
    public static void Main(string[] args)
    {
        NETNM nmm = new NETNM();
        nmm.RUN();
    }
}
class NETNM
{
    public void RUN()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                Console.WriteLine(ip.ToString());
            }
        }
    }
}

 

Spy++을 이용하면 특정윈도우핸들에 보낸 메세지(WM_KEYDOWN + VK_ESCAPE)가 나타남을 확인할수 있다.

 

/*
1. 목적: A라는 대상 Utility의 기능들을 B라는 다른 Utility에서
Window Message(SendMessage)를 통해 제어하는 방법과 실험을 실시.

2. 구현 - 간략 설명.
A.EXT : SPY++로 Caption Title을 찾아 FindWindow로 핸들을 찾아와,

SendMessage로 해당 핸들에 메세지 및 W/L param를 전송한다.
3. 구현 - 코드
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Xml;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

class Program
{
    public static void Main(string[] args)
    {
        Application.Run(new KAKAONM());
    }
}
class KAKAONM : Form
{
    [DllImport("user32.dll")]public static extern int FindWindow(string lpClassName, string lpWindowName);
    [DllImport("user32.dll")]public static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);


    const int WM_KEYDOWN = 0x0100;
    const int VK_ESCAPE = 0x1B;

    public DialogResult InputBox(string title, string content, ref string value)
    {
        Form form = new Form();
        PictureBox picture = new PictureBox();
        Label label = new Label();
        TextBox textBox = new TextBox();
        Button buttonOk = new Button();
        Button buttonCancel = new Button();

        form.ClientSize = new Size(300, 100);
        form.Controls.AddRange(new Control[] { label, picture, textBox, buttonOk, buttonCancel });
        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.StartPosition = FormStartPosition.CenterScreen;
        form.MaximizeBox = false;
        form.MinimizeBox = false;
        form.AcceptButton = buttonOk;
        form.CancelButton = buttonCancel;
        
        form.Text = title;
        picture.SizeMode = PictureBoxSizeMode.StretchImage;
        label.Text = content;
        textBox.Text = value;
        buttonOk.Text = "확인";
        buttonCancel.Text = "취소";

        buttonOk.DialogResult = DialogResult.OK;
        buttonCancel.DialogResult = DialogResult.Cancel;

        picture.SetBounds(10, 10, 50, 50);
        label.SetBounds(65, 17, 200, 20);
        textBox.SetBounds(65, 40, 220, 20);
        buttonOk.SetBounds(135, 70, 70, 20);
        buttonCancel.SetBounds(215, 70, 70, 20);

        DialogResult dialogResult = form.ShowDialog();

        value = textBox.Text;
        return dialogResult;
    }
    public KAKAONM()
    {
        //
    }
    protected override bool ProcessCmdKey(ref Message message, Keys keyData)
    {
        switch (message.Msg)
        {
            case WM_KEYDOWN:
                if (keyData.ToString() == "Escape")
                {
                     Application.Exit();
                }
                else if (keyData.ToString() == "Space")
                {
                      //
                }
                else if (keyData.ToString() == "Return")
                {
                    string HEXAVALUE = "";
                    int VALUE10 = 0;
                    IntPtr HANDLENM  = IntPtr.Zero;

                    if (InputBox("HEXA CODE", "VALUE", ref HEXAVALUE) == DialogResult.OK)
                    {
                        VALUE10 = Convert.ToInt32(HEXAVALUE, 16);
                        Console.WriteLine(VALUE10.ToString());

                        HANDLENM = Marshal.StringToHGlobalAuto(HEXAVALUE);
                        Console.WriteLine(HANDLENM.ToString() + "");

                        //SendMessage(HANDLENM, WM_KEYDOWN, VK_ESCAPE, 0);
                        // [DllImport("user32.dll")]public static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);에 선언되어진 입력데이타 파라미터를 준수함.
                        SendMessage(VALUE10, WM_KEYDOWN, VK_ESCAPE, 0);
                    }
                }
                break;
            default:
                break;
        }
        return base.ProcessCmdKey(ref message, keyData);
    }
}








case1)
gcc -c send.c
gcc -o send send.o -lws2_32

case2)
gcc -o send send.o -lwsock32

/*
C:\Users\Downloads>gcc -c a12.c
a12.c: In function 'main':
a12.c:8:2: warning: implicit declaration of function 'scanf_s' [-Wimplicit-function-declaration] scanf_s("%s", NN, sizeof(NN));

*/

해당 오류는 VSCode에서 scanf_s 함수를 사용했을 때 발생한다.
scanf_s는 기존 scanf 함수에 비해 보안이 강화된 함수로 Visual Studio에만 내장되어 있는 함수이다.
따라서 사용하기 위해선 해당 헤더를 따로 추가해주어야 한다.

/*
소스
*/
#include <stdio.h>

int main(int argc, char *argv[])
{
    char NN[5];

    printf(">>");
    scanf_s("%s", NN, sizeof(NN));
    printf(">>[%s]\n",NN);

    return 0;
}

 

/*
문제
'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다.
게임은 NxN 정사각 보드위에서 진행되고, 몇몇 칸에는 사과가 놓여져 있다. 보드의 상하좌우 끝에 벽이 있다. 게임이 시작할때 뱀은 맨위 맨좌측에 위치하고 뱀의 길이는 1 이다. 뱀은 처음에 오른쪽을 향한다.
뱀은 매 초마다 이동을 하는데 다음과 같은 규칙을 따른다.

먼저 뱀은 몸길이를 늘려 머리를 다음칸에 위치시킨다.
만약 벽이나 자기자신의 몸과 부딪히면 게임이 끝난다.
만약 이동한 칸에 사과가 있다면, 그 칸에 있던 사과가 없어지고 꼬리는 움직이지 않는다.
만약 이동한 칸에 사과가 없다면, 몸길이를 줄여서 꼬리가 위치한 칸을 비워준다. 즉, 몸길이는 변하지 않는다.
사과의 위치와 뱀의 이동경로가 주어질 때 이 게임이 몇 초에 끝나는지 계산하라.

입력
첫째 줄에 보드의 크기 N이 주어진다. (2 ≤ N ≤ 100) 다음 줄에 사과의 개수 K가 주어진다. (0 ≤ K ≤ 100)
다음 K개의 줄에는 사과의 위치가 주어지는데, 첫 번째 정수는 행, 두 번째 정수는 열 위치를 의미한다. 사과의 위치는 모두 다르며, 맨 위 맨 좌측 (1행 1열) 에는 사과가 없다.
다음 줄에는 뱀의 방향 변환 횟수 L 이 주어진다. (1 ≤ L ≤ 100)
다음 L개의 줄에는 뱀의 방향 변환 정보가 주어지는데, 정수 X와 문자 C로 이루어져 있으며. 게임 시작 시간으로부터 X초가 끝난 뒤에 왼쪽(C가 'L') 또는 오른쪽(C가 'D')로 90도 방향을 회전시킨다는 뜻이다. X는 10,000 이하의 양의 정수이며, 방향 전환 정보는 X가 증가하는 순으로 주어진다.
*/

using System;
using System.IO;
using System.Timers;

class Program
{
    public static void Main(string[] args)
    {
        if(args.Length == 1)
        {
            SNAKENM nm = new SNAKENM();
            nm.RUN("EX");
        }
        else
        {
            SNAKENM nm = new SNAKENM();
            nm.RUN();
        }
    }
}       
class SNAKENM
{
    static int MAPY = 100;
    static int MAPX = 100;

    const int LEFT = 1000;
    const int RIGHT = 1001;
    const int DOWN = 1002;
    const int UP = 1003;
    const int ROTATION_DEGREE_90_RIGHT = 10;
    const int ROTATION_DEGREE_90_LEFT = 20;
    const int EXIT_EVENT = -99;
    const int APPLE_EVENT = 2;
    const int APPLE_DELETE_EVENT = 3;

    int[] TIMER_EVENT = new int[1024];
    int[] TIMER_EVENT_DETAIL = new int[1024];
    int TIMER_EVENT_CNT=0;
    int timer_index = 0;

    int[,] APPLE = new int[MAPY,MAPX];
    int draw_apple_event = 0;
    int[,] BOARD = new int[MAPY,MAPX];
    int[] BOARD_POSITION_X = new int[MAPX];
    int[] BOARD_POSITION_Y = new int[MAPY];
    int position_index=0;
    int apple_delete_event_index=0;
    int APPLE_CNT=0;

    int xpos = 1;
    int ypos = 1;
    int direction = LEFT;
    int timer = 0;

    Timer tm = new Timer();

    public void RUN()
    {
        DATA_READ();
        DATA_INIT();
        TIME_INIT();

        ConsoleKeyInfo keyInfo;
        while(true)
        {
            keyInfo=Console.ReadKey(true);
            if(keyInfo.Key == ConsoleKey.Escape) break;
        }
    }
    void TIME_TICK(object sender, ElapsedEventArgs e)
    {
        timer++;

        if(direction == LEFT) xpos++;
        else if(direction == RIGHT) xpos--;
        else if(direction == UP) ypos--;
        else if(direction == DOWN) ypos++;

        if( (BOARD[ypos,xpos]==EXIT_EVENT) || (BOARD[ypos,xpos]==1))
        {
            tm.Stop();
            tm=null;
            Console.WriteLine("[TIME]:" + timer.ToString("00000"));
            Environment.Exit(0);
        }

        //APPLE EVENT
        if(APPLE[ypos,xpos]==APPLE_EVENT)
        {
            draw_apple_event = APPLE_EVENT;
            APPLE[ypos,xpos]=APPLE_DELETE_EVENT;

            if(direction == LEFT) xpos--;
            else if(direction == RIGHT) xpos++;
            else if(direction == UP) ypos++;
            else if(direction == DOWN) ypos--;
        }
        else if(APPLE[ypos,xpos]==APPLE_DELETE_EVENT)
        {
            draw_apple_event = APPLE_DELETE_EVENT;

            //마지막꼬리의 값을 없앤다.
            int xx = BOARD_POSITION_X[apple_delete_event_index];
            int yy = BOARD_POSITION_Y[apple_delete_event_index];
            BOARD[yy,xx] = 0;
            apple_delete_event_index++;
        }
        else
        {
            draw_apple_event = 0;
        }

        BOARD[ypos,xpos]=1;
        BOARD_POSITION_X[position_index] = xpos;
        BOARD_POSITION_Y[position_index] = ypos;
        position_index++;

        if(timer == TIMER_EVENT[timer_index])
        {
            if(TIMER_EVENT_DETAIL[timer_index]==ROTATION_DEGREE_90_LEFT)
            {
                if(direction==LEFT) direction = UP;
                else if(direction==UP) direction = RIGHT;
                else if(direction==RIGHT) direction = DOWN;
                else if(direction==DOWN) direction = LEFT;
            }
            else if(TIMER_EVENT_DETAIL[timer_index]==ROTATION_DEGREE_90_RIGHT)
            {
                if(direction==LEFT) direction = DOWN;
                else if(direction==UP) direction = LEFT;
                else if(direction==RIGHT) direction = UP;
                else if(direction==DOWN) direction = RIGHT;
            }
            timer_index++;
        }

        DRAW();
    }
    public void RUN(string EX)
    {
        DATA_INIT(EX);
        TIME_INIT();

        ConsoleKeyInfo keyInfo;
        while(true)
        {
            keyInfo=Console.ReadKey(true);
            if(keyInfo.Key == ConsoleKey.Escape) break;
        }
    }
    void DATA_READ()
    {
        string inputText = "";
        int index = 0;

        while(true)
        {
            if(index == 0)
            {
                Console.WriteLine("1. MAPY * MAPX");
                inputText = Console.ReadLine();

                MAPX=Convert.ToInt32(inputText) + 2;
                MAPY=Convert.ToInt32(inputText) + 2;
            }
            else if(index == 1)
            {
                Console.WriteLine("2. APPLE_CNT");
                inputText = Console.ReadLine();

                APPLE_CNT=Convert.ToInt32(inputText);
            }
            else if(index == 2)
            {
                for(int ii=0; ii<APPLE_CNT; ii++)
                {
                    Console.WriteLine("3. APPLE_POSITION:[" + (ii+1).ToString("00") + "]");
                    inputText = Console.ReadLine();

                    string[] position = (inputText).Split(' ');
                    if(position.Length != 2)
                    {
                        Console.WriteLine("invalid data error!!");
                        Environment.Exit(0);
                    }

                    int yy = Convert.ToInt32(position[0]) + 1;
                    int xx = Convert.ToInt32(position[1]) + 1;

                    APPLE[yy,xx]=APPLE_EVENT;
                }
            }
            else if(index == 3)
            {
                Console.WriteLine("4. TIMER_EVENT_CNT");
                inputText = Console.ReadLine();

                TIMER_EVENT_CNT=Convert.ToInt32(inputText);
            }
            else if(index == 4)
            {
                for(int ii=0; ii<TIMER_EVENT_CNT; ii++)
                {
                    Console.WriteLine("5. TIMER EVENT DETAIL:[" + (ii+1).ToString("00") + "]");
                    inputText = Console.ReadLine();     

                    string[] position = (inputText).Split(' ');
                    if(position.Length != 2)
                    {
                        Console.WriteLine("invalid data error!!");
                        Environment.Exit(0);
                    }

                    TIMER_EVENT[ii] = Convert.ToInt32(position[0]);
                    if(position[1] == "L") TIMER_EVENT_DETAIL[ii] = ROTATION_DEGREE_90_LEFT;
                    else if(position[1] == "D") TIMER_EVENT_DETAIL[ii] = ROTATION_DEGREE_90_RIGHT;
                }
                break;
            }
            index++;
        }
    }
    void DATA_INIT(string EX)
    {
        MAPX = 10 + 2;
        MAPY = 10 + 2;

        APPLE[1,5]=APPLE_EVENT;
        APPLE[1,3]=APPLE_EVENT;
        APPLE[1,2]=APPLE_EVENT;
        APPLE[1,6]=APPLE_EVENT;
        APPLE[1,7]=APPLE_EVENT;

        TIMER_EVENT[0]=8;
        TIMER_EVENT_DETAIL[0]=ROTATION_DEGREE_90_RIGHT;

        TIMER_EVENT[1]=10;
        TIMER_EVENT_DETAIL[1]=ROTATION_DEGREE_90_RIGHT;

        TIMER_EVENT[2]=11;
        TIMER_EVENT_DETAIL[2]=ROTATION_DEGREE_90_RIGHT;

        TIMER_EVENT[3]=13;
        TIMER_EVENT_DETAIL[2]=ROTATION_DEGREE_90_LEFT;

        for(int ii=0; ii<MAPY; ii++)
        {
        BOARD[ii,0]=-99;
        BOARD[ii,MAPX-1]=-99;
        }
        for(int kk=0; kk<MAPX; kk++)
        {
        BOARD[0,kk]=-99;
        BOARD[MAPY-1,kk]=-99;
        }
        BOARD[ypos,xpos]=1;
        BOARD_POSITION_X[position_index] = xpos;
        BOARD_POSITION_Y[position_index] = ypos;
        position_index++;
    }
    void DATA_INIT()
    {
        for(int ii=0; ii<MAPY; ii++)
        {
            BOARD[ii,0]=-99;
            BOARD[ii,MAPX-1]=-99;
        }
        for(int kk=0; kk<MAPX; kk++)
        {
        BOARD[0,kk]=-99;
        BOARD[MAPY-1,kk]=-99;
        }
        BOARD[ypos,xpos]=1;
    }
    void TIME_INIT()
    {
        tm.Elapsed += new ElapsedEventHandler(TIME_TICK);
        tm.Interval = 1000;
        tm.Start();
    }   
    void DRAW()
    {
        string mmmText = "";

        mmmText += "[" + timer.ToString("00000") + "]" + ",EVENT[" + draw_apple_event.ToString("00000") + "]" + ",X[" + ypos.ToString("00000") + "]" + ",Y[" + xpos.ToString("00000") + "]" + "\n";
        for(int ii=0; ii<MAPY; ii++)
        {
            for(int kk=0; kk<MAPX; kk++)
            {
                if(BOARD[ii,kk]==1) mmmText += "[**]";
                else mmmText += ii.ToString("00") + kk.ToString("00");
            }
            mmmText += "\n";
        }
        Console.WriteLine(mmmText);
        Console.WriteLine("");
    }
}

 

 

파일첨부)

snake2.cs
0.01MB

+ Recent posts