반응형

 


 


테스트한 날짜:  2023년 2월 20일

 

 

 

DD 명령으로 Storage I/O 성능 확인

 

############################################################################
## 쓰기(output) 성능 확인
############################################################################

## Case: 저장 장치의 Cache memory(즉, Buffer memory)를 사용하는 경우
$ dd if=/dev/zero bs=1024 count=5000 of=/mnt/hdd1/my_test_file
5000+0 records in
5000+0 records out
5120000 bytes (5.1 MB, 4.9 MiB) copied, 0.0113672 s, 450 MB/s
$

## Case: 저장 장치의 Cache memory(즉, Buffer memory)를 사용하지 않는 경우,
##       oflag=direct  옵션을 추가한다.
$ dd if=/dev/zero bs=1024 count=5000 of=/mnt/hdd1/my_test_file oflag=direct
5000+0 records in
5000+0 records out
5120000 bytes (5.1 MB, 4.9 MiB) copied, 0.23691 s, 21.6 MB/s


############################################################################
## 읽기(input) 성능 확인
############################################################################

$ dd if=/mnt/hdd1/my_test_file of=/dev/null bs=1024
5000+0 records in
5000+0 records out
5120000 bytes (5.1 MB, 4.9 MiB) copied, 0.0123259 s, 415 MB/s
$

 

 


 

반응형

 

작성일: 2024년 2월 16일

 

방법 A)  timedatectl 명령으로 시스템 전체의 timezone 변경하기

##
## 세계의 모든 timezone 확인하기
##

$ timedatectl list-timezones
Africa/Abidjan
Africa/Accra
...
Asia/Seoul
Asia/Shanghai
Asia/Singapore
...

##
## 서울 시간대로 변경하기
##

$ timedatectl set-timezone Asia/Seoul




##
## timezone이 잘 변경되었는지 확인한다.
##
$ timedatectl show

Timezone=Asia/Seoul
LocalRTC=no
CanNTP=yes
NTP=yes
NTPSynchronized=yes
TimeUSec=Wed 2023-03-15 09:45:38 KST
RTCTimeUSec=Wed 2023-03-15 09:45:38 KST


$ timedatectl status

               Local time: Wed 2023-03-15 09:45:41 KST
           Universal time: Wed 2023-03-15 00:45:41 UTC
                 RTC time: Wed 2023-03-15 00:45:41
                Time zone: Asia/Seoul (KST, +0900)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
          
$

 

 

방법 B)  환경 변수로 timezone 변경하기

$  cat .bashrc
... 중간 생략 ...
export TZ=Asia/Seoul

$

 

 

 

 

 

반응형

 


작성일: 2024년 4월 24일

 

 

 

Ubuntu 기본 패키지를 설치하고, 부팅할 때 아래와 같이 Network 설정 화면에서 오랜 시간 대기하는 경우가 있다.

A start job is running for wait for network to be configured

 

일단, 부팅되면 root 계정으로 아래와 같이 설정을 수정하고 reboot하면, 빠르게 부팅될 것이다.

 

##
## Network connection을 기다라지 않기 위해 아래와 같이 
## systemd-networkd-wait-online.service 서비스를 비활성화한다.
##
$  systemctl disable systemd-networkd-wait-online.service

##
## 다른 서비스에 의해서 systemd-networkd-wait-online.service 서비스가 활성화되는 것을 막기 위해
## 아래와 같이 systemd-networkd-wait-online.service 서비스를 masking한다.
##
$  systemctl mask systemd-networkd-wait-online.service

 

 

참고: 
  DHCP 설정 Off는 위 이슈와 관련은 없지만, 0.1초라도 부팅 시간을 줄이고자 한다면 DHCP를 off하는 것이 좋다.
  (물론, DHCP를 사용할 일이 없을 때만~~~)
##
## DHCP로 IP address 설정할 필요가 없다면, DHCP 기능을 끈다.
##
$  cat /etc/netplan/00-installer-config.yaml

... 중간 생략 ...

    enp7s0:
      dhcp4: false
      
... 중간 생략 ...

$

 


 

게시물 작성자: sejong.jeonjo@gmail.com

 

 

반응형

 


 

테스트한 날짜:  2024년 2월 20일
테스트에 사용한 OS: Ubuntu 22.04

 

Linux 장비를 PPTP Client로 사용하기 위한 방법

Client 입장에서 Linux PC를 PPTP 서버와 GRE Tunnel을 생성하는 방법이다.

 

전제 조건:
    아래 PPTP Client 예제를 수행하기 전에 PPTP 서버가 이미 구성되어 있어야 한다. 
    IPTIME 같은 인터넷 공유기에 PPTP 서버 기능이 있으니까, 쉽게 테스트하려면 IPTIME 공유기를 이용하는 것이 좋다.

 

잠깐 !!
Linux 장비(Ubuntu 22.04)에 PPTP Server를 구축할 계획이라면, 아래 문서를 참고하기 !

 

       https://andrewpage.tistory.com/361

 

##########################################################
## Client Linux OS에서 아래의 명령을 수행
##########################################################

##########################################################
## pptp 관련 패키지를 설치한다.
##########################################################
$  sudo apt install pptp-linux


##########################################################
## /etc/ppp/options 파일을 편집한다.
##########################################################
$  cat  /etc/ppp/options

lock
noauth
nobsdcomp
nodeflate
refuse-pap
refuse-eap
refuse-chap
refuse-mschap
mtu 1400

$

##########################################################
## /etc/ppp/chap-secrets 파일을 편집한다.
##########################################################
$  cat  /etc/ppp/chap-secrets

sejong  PPTP  "my-password" *

$

##########################################################
##  /etc/ppp/peers/sejong 파일을 편집한다.
##########################################################
$  cat  /etc/ppp/peers/sejong

pty "pptp 55.123.12.123 --nolaunchpppd"
name sejong
remotename PPTP
file /etc/ppp/options
ipparam sejong




##########################################################
## << 참고:  이 작업은 필요한 경우만 할 것 !!! >>
##
## 이 내용은 꼭 필요한 것은 아닌데, ppp0 tunnel port가 생성되고 IP address가 설정되고 나서
## static routing table에 추가하고 싶은 내용이 있다면, 
## 아래와 같이 ip-up 파일에 route 명령을 추가한다. 
## (이렇게 하는 것이 정석적 방법인지는 모르겠다.  일단, 나는 이렇게 사용하고 있다.)
##########################################################
$  cat  /etc/ppp/ip-up

... (중간 생략) ...
ip route add 192.168.0.0/24 dev ppp0    # <-- 나는 이 내용을 추가했다.

$


##########################################################
## 이제 설정 작업은 모두 끝났다. pon 명령을 실행하면 잘 동작할 것이다. ^^
##########################################################

##########################################################
## 위에서 설정한 파일을 이용하여 PPTP 서버와 GRE 터널을 만든다.
## 참고로 pon 명령은 "ppp on"을 줄인 말이다.
##########################################################
$  pon  sejong  debug  dump  logfd 2  nodetach

...
...
local  IP address 192.168.0.220
remote IP address 192.168.0.1
Script /etc/ppp/ip-up started (pid 14290)
Script /etc/ppp/ip-up finished (pid 14290), status = 0x0

 

참고로, 위 pon 명령을 수행하면 명령행 prompt가 출력되지 않는다.
왜냐하면 pon 명령이 백그라운드로 동작하는 것이 아니기 때문에 pod 명령을 수행한 터미널은 이 상태로 두고,
다른 터미널을 하나 더 열어서 작업해야 한다.
새 터미널에서 아래와 같이 VPN 서버 쪽으로 ping을 보내본다.

 

$  ping 192.168.0.1

ing 192.168.0.1 -c 1
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=4.45 ms

--- 192.168.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 4.448/4.448/4.448/0.000 ms

$

 

 


 

PPTP 및 GRE Tunnel 설정 관련 문서

 

 

PPTP Client - ArchWiki

pptpclient is a program implementing the Microsoft PPTP protocol. As such, it can be used to connect to a Microsoft VPN network (or any PPTP-based VPN) provided by a school or workplace. Installation Install the pptpclient package. Configure To configure p

wiki.archlinux.org

 

 


 

반응형

 


 

작성일: 2023년 12월 11일

 

 

Ubuntu 20.04 또는 Ubuntu 22.04에 Samba(SMB) 서버를 설치하고 싶다면 아래 절차를 따라하면 잘 동작한다.

  

 

##
##  Samba 서버 프로그램을 설치한다.
##
$  sudo apt-get install -y samba

...

##
##  Samba 서버가 공유할 폴더(디렉토리) 정보를 설정한다.
##
$  vi /etc/samba/smb.conf
... 중간 생략 ...
;
; 아래 내용을 추가한다.
;
[mybox]
   comment = My File Box
   path = /home/sejong
   guest ok = no
   browseable = yes
   writable = yes
   create mask = 0777
   directory mask = 0777
   valid users = sejong
... 중간 생략 ...

##
## Linux 계정 'sejong'을 samba 접근 계정으로 추가한다.
## 암호는 Linux 계정 'sejong'의 암호와 달라도 된다.
##
$  sudo smbpasswd -a sejong

##
## Samba 서버 데몬을 재기동한다.
##
$  sudo /etc/init.d/smbd restart
## 또는 위 명령을 아래와 같이 수행해도 된다.
##  $ sudo  systemctl restart smbd

 

클라이언트 PC에서 아래와 같이 Samba 서버에 접속시도한다. (아래는 Macbook에서 실행한 화면)

 

Macbook에서 Samba 서버에 접속 시도

 

 

 

 

Samba 서버 설정 끝 !!!
Samba 서버 관리 명령을 알고 싶다면, 아래 내용을 더 읽어보아요~~

 

 

 

Samba 계정 정보를 보고 싶다면, 아래와 같이 `pdbedit` 명령으로 조회할 수 있다.

 

$  pdbedit -L -v

---------------
Unix username:        sejong
NT username:
Account Flags:        [U          ]
Home Directory:       \\ANDREW-UBUNTU\sejong
HomeDir Drive:
Logon Script:
Profile Path:         \\ANDREW-UBUNTU\sejong\profile
Domain:               ANDREW-UBUNTU
Account desc:
Workstations:
Munged dial:
Logon time:           0
Logoff time:          Thu, 07 Feb 2036 00:06:39 KST
Kickoff time:         Thu, 07 Feb 2036 00:06:39 KST
Password last set:    Wed, 07 Dec 2022 16:06:30 KST
Password can change:  Wed, 07 Dec 2022 16:06:30 KST
Password must change: never
Last bad password   : 0
Bad password count  : 0
Logon hours         : FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

$

 

 

Samba 서버에 접속한 Client 정보를 보고 싶다면 아래와 같이 `smbstatus` 명령을 사용한다.

$  smbstatus

Samba version 4.15.9-Ubuntu
PID     Username     Group        Machine                                   Protocol Version  Encryption           Signing
----------------------------------------------------------------------------------------------------------------------------------------
295419  sejong       sejong       10.1.3.169 (ipv4:10.1.3.169:63352)        SMB3_11           -                    partial(AES-128-CMAC)

Service      pid     Machine       Connected at                     Encryption   Signing
---------------------------------------------------------------------------------------------
mybox        295419  10.1.3.169    Wed Dec  7 04:23:23 PM 2022 KST  -            -


Locked files:
Pid          User(ID)   DenyMode   Access      R/W        Oplock           SharePath   Name   Time
--------------------------------------------------------------------------------------------------
295419       1001       DENY_NONE  0x100081    RDONLY     NONE             /home/sejong   .   Wed Dec  7 16:23:22 2022

 

 

계정 정보를 변경하고 싶다면,  `usermod` 명령을 사용한다.

 

$  usermod --help
Usage: usermod [options] LOGIN

Options:
  -b, --badnames                allow bad names
  -c, --comment COMMENT         new value of the GECOS field
  -d, --home HOME_DIR           new home directory for the user account
  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE
  -f, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -g, --gid GROUP               force use GROUP as new primary group
  -G, --groups GROUPS           new list of supplementary GROUPS
  -a, --append                  append the user to the supplemental GROUPS
                                mentioned by the -G option without removing
                                the user from other groups
  -h, --help                    display this help message and exit
  -l, --login NEW_LOGIN         new value of the login name
  -L, --lock                    lock the user account
  -m, --move-home               move contents of the home directory to the
                                new location (use only with -d)
  -o, --non-unique              allow using duplicate (non-unique) UID
  -p, --password PASSWORD       use encrypted password for the new password
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files
  -s, --shell SHELL             new login shell for the user account
  -u, --uid UID                 new UID for the user account
  -U, --unlock                  unlock the user account
  -v, --add-subuids FIRST-LAST  add range of subordinate uids
  -V, --del-subuids FIRST-LAST  remove range of subordinate uids
  -w, --add-subgids FIRST-LAST  add range of subordinate gids
  -W, --del-subgids FIRST-LAST  remove range of subordinate gids
  -Z, --selinux-user SEUSER     new SELinux user mapping for the user account

 

 

게시물 작성자: sejong.jeonjo@gmail.com

 

 


 

반응형

 

 

Ubuntu OS를 설치한 후, Network 구성을 바꿀 때 nmtui, netplan, nm-connection-editor 등 CLI 명령을 사용하면 쉽게 network 구성을 설정할 수 있다.

 

nmtui 명령

메모: 지금은 바빠서 설명을 생략.  나중에 내용을 추가할 것 !!
$ nmtui

Text Terminal에서 위 명령을 수행하면, 아래와 같이 동일 Text Terminal에서 TUI가 뜬다.

nmtui 시작 화면

 

 

netplan 명령

길게 설명하는 것보다는 아래 예시를 보고 이해하고 따라하는 것이 좋을 듯 ~~~

 

 

Case A:
만약 Gnome Desktop GUI의 [ Settings ] - [ Network ] - [ Wired ] 화면에서 설정하고 싶으면,
아래와 같이 renderer를 NetworkManager로 지정하고 아무것도 설정하지 않으면 된다.
그러면 NetworkManager가 알아서 Physical Network Device를 찾아서 Profiling할 것이다.

 

$  cat  /etc/netplan/00-installer-config.yaml

network:
    renderer: NetworkManager
    version: 2
    
$  netplan  apply

 

Case B:
만약 Gnome Desktop GUI의 [ Settings ] - [ Network ] - [ Wired ] 화면에서 설정한 값을 무시하고
설정 파일에 있는 Network Config를 적용하고 싶다면, 
아래와 같이 renderer를 networkd 로 지정한다. 그런 후에 원하는 설정을 추가한다.
$  cat  /etc/netplan/00-installer-config.yaml

network:
    renderer: networkd
    version: 2
    ethernets:
        enp4s0:
            addresses:
                - 0.0.0.0/32
        br-ex:
            addresses:
                - 10.1.3.166/24
            nameservers:
                addresses: [8.8.8.8, 8.8.4.4]
            routes:
                - to: default
                  via: 10.1.3.1
        br-ex:                  
            dhcp4: true
 
$  netplan apply

## 설정 파일(YAML)에 에러가 없으면, 아무것도 출력하지 않는다.

$

 

 

 

nm-connection-editor 명령

SSH로 접속한 Text Terminal에서는 실행하면 안 되고, 원격 데스크탑(Remote Desktop)으로 접속했거나 Console Monitor를 사용한 경우에만 nm-connection-editor가 동작한다.

 

nm-connection-editor 시작 화면

 

 

게시물 작성자: sejong.jeonjo@gmail.com

 

 

 

반응형

 


  

작성일: 2024년 5월 3일

 

 

참고:
  Ubunut 24.04에서 한영 전환 설정하는 방법이 궁금하다면 아래 블로그를 보는 것을 추천 !!!

      Ubuntu 24.04 에서 한영 전환 설정하는 방법 -->  https://andrewpage.tistory.com/390

 

Ubuntu 24.04 한글 입력기 설정 (한영 변환 설정)

작성일: 2024년 5월 3일   Ubuntu 24.04를 설치하고 한글 입력기 설정할 때 헷갈려서 메모를 남겨본다.처음에는 한영 전환 설정하는 방법을 잘 몰라서 설정 화면에서 이것저것 다 해봐도 잘 안 되었

andrewpage.tistory.com

 

 

 


 

Ubuntu 22.04(또는 Ubuntu 24.04)를 설치하고 한글 입력기 설정할 때 헷갈려서 메모를 남겨본다. 

처음에는 한영 전환 설정하는 방법을 잘 몰라서 설정 화면에서 이것저것 다 해봐도 잘 안 되었다.

 

!!! 한글 입력을 위해 설정해야 할 핵심은 키보드가 "Korean -> Korean"이 아니라 "Korean -> Hangul" 이라는 것 !!!

 

아래에 설명된 설정 순서를 따라해보면 한글 입력이 잘 될 것이다. ^^

 


 

Step 1 :  한글 입력 방식 추가 (Korean -> Hangul)

1)  Terminal에서 `ibus-setup` 명령을 실행 (아래 화면을 똑같이 따라할 것 !!)

 

Ubuntu 22.04 한글 입력 설정

 

2)  위 IBus Preference 화면에서 [Input Method] 탭을 선택하고, "Korean-Hangul"을 추가.

주의:
  꼭 Korean -> Hangul을 추가해야 한다. 비슷한 항목인 Korean을 선택하면 안 된다.

 

 

Step 2 : 한영 변환 키보드 조합 설정 (Input Sources 설정)

 

이렇게 한글 입력을 위한 설정을 하고 나면, [Keyboard] 설정 화면에서 한영 변환을 위한 키보드 조합을 설정해야 한다.

(아래 화면을 참고하여 따라할 것 !!)

 


참고로, 나는 MacBook에서 [ Shift ] + [ Space ] 키 조합으로 한영 변환하는 습관이 있어서 Ubuntu 22.04도 똑같이 한영 변환 키보드 조합을 설정한 것이다.
아래 설정화면에서 본인이 편한 키보드 조합으로 한영 변환을 설정하면 된다.

Ubuntu 22.04 한영 전환 설정

 

 

 

설정 끝 !
한영 전환이 잘 될 것이다. ^^


 

한번 더 위 설정 화면을 간단하게 글로 설명하면, 아래와 같다. (위에서 그림으로 설명한 것과 똑같은 내용이다)

 

1)  [ Settings ] 화면에서 [ Keyboard ] 선택

2)  [ Input Sources ] 화면에서 [ Korean (Hangul) ] 선택 후, [ Preferences ] 클릭

3)  [ IBusHangul Setup ] 화면이 열리면, [ Hangul ] 탭 선택

4)  Hangul Toggle Key 항목에서 한영 변환을 위한 키보드 조합 추가  

      (나는 내 개인 취향상, [ Shift Key + Space Key ]로 설정했음)

5)  OK 버튼을 누르면, 모든 설정 끝 !!!

 


 

 

블로그 작성자: sejong.jeonjo@gmail.com
반응형

Go Language로 특정 Process의 CPU, Memory 사용량을 계산하고 싶다면,

아래의 코드를 Build해서 사용하면 된다.

 

참고: Linux, MacOS, Unix, Windows 모두 동작하는 코드임.

 

 

// Filename: proc_usage.go

package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"math"
	"os/exec"
	"path"
	"runtime"
	"strconv"
	"strings"
	"sync"
)

const (
	statTypePS   = "ps"
	statTypeProc = "proc"
)

// SysInfo will record cpu and memory data
type SysInfo struct {
	CPU    float64
	Memory float64
}

// Stat will store CPU time struct
type Stat struct {
	utime  float64
	stime  float64
	cutime float64
	cstime float64
	start  float64
	rss    float64
	uptime float64
}

type fn func(int) (*SysInfo, error)

var fnMap map[string]fn
var platform string
var history map[int]Stat
var historyLock sync.Mutex
var eol string

// Linux platform
var clkTck float64 = 100    // default
var pageSize float64 = 4096 // default

func init() {
	platform = runtime.GOOS
	if eol = "\n"; strings.Index(platform, "win") == 0 {
		platform = "win"
		eol = "\r\n"
	}
	history = make(map[int]Stat)
	fnMap = make(map[string]fn)
	fnMap["darwin"] = wrapper("ps")
	fnMap["sunos"] = wrapper("ps")
	fnMap["freebsd"] = wrapper("ps")
	fnMap["openbsd"] = wrapper("proc")
	fnMap["aix"] = wrapper("ps")
	fnMap["linux"] = wrapper("proc")
	fnMap["netbsd"] = wrapper("proc")
	fnMap["win"] = wrapper("win")

	if platform == "linux" || platform == "netbsd" || platform == "openbsd" {
		initProc()
	}
}

func initProc() {
	clkTckStdout, err := exec.Command("getconf", "CLK_TCK").Output()
	if err == nil {
		clkTck = parseFloat(formatStdOut(clkTckStdout, 0)[0])
	}

	pageSizeStdout, err := exec.Command("getconf", "PAGESIZE").Output()
	if err == nil {
		pageSize = parseFloat(formatStdOut(pageSizeStdout, 0)[0])
	}

}

func wrapper(statType string) func(pid int) (*SysInfo, error) {
	return func(pid int) (*SysInfo, error) {
		return stat(pid, statType)
	}
}

func formatStdOut(stdout []byte, userfulIndex int) []string {
	infoArr := strings.Split(string(stdout), eol)[userfulIndex]
	ret := strings.Fields(infoArr)
	return ret
}

func parseFloat(val string) float64 {
	floatVal, _ := strconv.ParseFloat(val, 64)
	return floatVal
}

func statFromPS(pid int) (*SysInfo, error) {
	sysInfo := &SysInfo{}
	args := "-o pcpu,rss -p"
	if platform == "aix" {
		args = "-o pcpu,rssize -p"
	}
	stdout, _ := exec.Command("ps", args, strconv.Itoa(pid)).Output()
	ret := formatStdOut(stdout, 1)
	if len(ret) == 0 {
		return sysInfo, errors.New("Can't find process with this PID: " + strconv.Itoa(pid))
	}
	sysInfo.CPU = parseFloat(ret[0])
	sysInfo.Memory = parseFloat(ret[1]) * 1024
	return sysInfo, nil
}

func statFromProc(pid int) (*SysInfo, error) {
	sysInfo := &SysInfo{}
	uptimeFileBytes, err := ioutil.ReadFile(path.Join("/proc", "uptime"))
	if err != nil {
		return nil, err
	}
	uptime := parseFloat(strings.Split(string(uptimeFileBytes), " ")[0])

	procStatFileBytes, err := ioutil.ReadFile(path.Join("/proc", strconv.Itoa(pid), "stat"))
	if err != nil {
		return nil, err
	}
	splitAfter := strings.SplitAfter(string(procStatFileBytes), ")")

	if len(splitAfter) == 0 || len(splitAfter) == 1 {
		return sysInfo, errors.New("Can't find process with this PID: " + strconv.Itoa(pid))
	}
	infos := strings.Split(splitAfter[1], " ")
	stat := &Stat{
		utime:  parseFloat(infos[12]),
		stime:  parseFloat(infos[13]),
		cutime: parseFloat(infos[14]),
		cstime: parseFloat(infos[15]),
		start:  parseFloat(infos[20]) / clkTck,
		rss:    parseFloat(infos[22]),
		uptime: uptime,
	}

	_stime := 0.0
	_utime := 0.0

	historyLock.Lock()
	defer historyLock.Unlock()

	_history := history[pid]

	if _history.stime != 0 {
		_stime = _history.stime
	}

	if _history.utime != 0 {
		_utime = _history.utime
	}
	total := stat.stime - _stime + stat.utime - _utime
	total = total / clkTck

	seconds := stat.start - uptime
	if _history.uptime != 0 {
		seconds = uptime - _history.uptime
	}

	seconds = math.Abs(seconds)
	if seconds == 0 {
		seconds = 1
	}

	history[pid] = *stat
	sysInfo.CPU = (total / seconds) * 100
	sysInfo.Memory = stat.rss * pageSize
	return sysInfo, nil
}

func stat(pid int, statType string) (*SysInfo, error) {
	switch statType {
	case statTypePS:
		return statFromPS(pid)
	case statTypeProc:
		return statFromProc(pid)
	default:
		return nil, fmt.Errorf("Unsupported OS %s", runtime.GOOS)
	}
}

// GetStat will return current system CPU and memory data
func GetStat(pid int) (*SysInfo, error) {
	sysInfo, err := fnMap[platform](pid)
	return sysInfo, err
}

 

 

 

// Filename: main.go

package main

import (
    "os"
    "fmt"
    "time"
    "strconv"
)

func main() {
    myPid, _ := strconv.Atoi(os.Args[1])

    for i:= 0; i < 100; i++ {
        sysInfo, _ := GetStat(myPid)
        fmt.Println("CPU Usage     :", sysInfo.CPU)
        fmt.Println("Mem Usage(RSS):", sysInfo.Memory)
        time.Sleep(5 * time.Second)
    }
}

 

위와 같이 Go source code를 모두 작성했다면, 아래처럼 build하고 실행하면 된다.

 

$ go mod init andrew.space/proc_usage
go: creating new go.mod: module andrew.space/proc_usage
go: to add module requirements and sums:
	go mod tidy
    
$ go mod tidy

$ go build

$ ./proc_usage 4314
CPU Usage     : 52.92167225853122
Mem Usage(RSS): 2.018664448e+09
CPU Usage     : 39.800000000000004
Mem Usage(RSS): 2.018664448e+09
CPU Usage     : 47.30538922366738
Mem Usage(RSS): 2.018664448e+09
...
...

 

top 명령으로 본 것과 결과가 동일했다.

+ Recent posts