2015년 2월 25일 수요일

Useful SQL queries

Date / Time related queries

  1. Get the first day of the month

    Quickly returns the first day of current month. Instead of current month you want to find first day of month where a date falls, replace SYSDATE with any date column/value.

    SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month"
        FROM DUAL;
  2. Get the last day of the month

    This query is similar to above but returns last day of current month. One thing worth noting is that it automatically takes care of leap year. So if you have 29 days in Feb, it will return 29/2. Also similar to above query replace SYSDATE with any other date column/value to find last day of that particular month.

    SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month"
        FROM DUAL;
  3. Get the first day of the Year

    First day of year is always 1-Jan. This query can be use in stored procedure where you quickly want first day of year for some calculation.

    SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;
  4. Get the last day of the year

    Similar to above query. Instead of first day this query returns last day of current year.

    SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL
  5. Get number of days in current month

    Now this is useful. This query returns number of days in current month. You can change SYSDATE with any date/value to know number of days in that month.

    SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days
      FROM DUAL;
  6. Get number of days left in current month

    Below query calculates number of days left in current month.

    SELECT SYSDATE,
           LAST_DAY (SYSDATE) "Last",
           LAST_DAY (SYSDATE) - SYSDATE "Days left"
      FROM DUAL;
  7. Get number of days between two dates

    Use this query to get difference between two dates in number of days.

    SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)
              num_of_days
      FROM DUAL;
     
    OR
     
    SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;

    Use second query if you need to find number of days since some specific date. In this example number of days since any employee is hired.

  8. Display each months start and end date upto last month of the year

    This clever query displays start date and end date of each month in current year. You might want to use this for certain types of calculations.

    SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,
           TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
      FROM XMLTABLE (
              'for $i in 0 to xs:int(D) return $i'
              PASSING XMLELEMENT (
                         d,
                         FLOOR (
                            MONTHS_BETWEEN (
                               ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
                               SYSDATE)))
              COLUMNS i INTEGER PATH '.');
  9. Get number of seconds passed since today (since 00:00 hr)

    SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
      FROM DUAL;
  10. Get number of seconds left today (till 23:59:59 hr)

    SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
      FROM DUAL;

    Data dictionary queries

  11. Check if a table exists in the current database schema

    A simple query that can be used to check if a table exists before you create it. This way you can make your create table script rerunnable. Just replace table_name with actual table you want to check. This query will check if table exists for current user (from where the query is executed).

    SELECT table_name
      FROM user_tables
     WHERE table_name = 'TABLE_NAME';
  12. Check if a column exists in a table

    Simple query to check if a particular column exists in table. Useful when you tries to add new column in table using ALTER TABLE statement, you might wanna check if column already exists before adding one.

    SELECT column_name AS FOUND
      FROM user_tab_cols
     WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
  13. Showing the table structure

    This query gives you the DDL statement for any table. Notice we have pass ‘TABLE’ as first parameter. This query can be generalized to get DDL statement of any database object. For example to get DDL for a view just replace first argument with ‘VIEW’ and second with your view name and so.

    SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
  14. Getting current schema

    Yet another query to get current schema name.

    SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
  15. Changing current schema

    Yet another query to change the current schema. Useful when your script is expected to run under certain user but is actually executed by other user. It is always safe to set the current user to what your script expects.

    ALTER SESSION SET CURRENT_SCHEMA = new_schema;

    Database administration queries

  16. Database version information

    Returns the Oracle database version.

    SELECT * FROM v$version;
  17. Database default information

    Some system default information.

    SELECT username,
           profile,
           default_tablespace,
           temporary_tablespace
      FROM dba_users;
  18. Database Character Set information

    Display the character set information of database.

    SELECT * FROM nls_database_parameters;
  19. Get Oracle version

    SELECT VALUE
      FROM v$system_parameter
     WHERE name = 'compatible';
  20. Store data case sensitive but to index it case insensitive

    Now this ones tricky. Sometime you might querying database on some value independent of case. In your query you might do UPPER(..) = UPPER(..) on both sides to make it case insensitive. Now in such cases, you might want to make your index case insensitive so that they don’t occupy more space. Feel free to experiment with this one.

    CREATE TABLE tab (col1 VARCHAR2 (10));
     
    CREATE INDEX idx1
       ON tab (UPPER (col1));
     
    ANALYZE TABLE a COMPUTE STATISTICS;
  21. Resizing Tablespace without adding datafile

    Yet another DDL query to resize table space.

    ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
  22. Checking autoextend on/off for Tablespaces

    Query to check if autoextend is on or off for a given tablespace.

    SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;
     
    (OR)
     
    SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;
  23. Adding datafile to a tablespace

    Query to add datafile in a tablespace.

    ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'
        SIZE 1000M AUTOEXTEND OFF;
  24. Increasing datafile size

    Yet another query to increase the datafile size of a given datafile.

    ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;
  25. Find the Actual size of a Database

    Gives the actual database size in GB.

    SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
  26. Find the size occupied by Data in a Database or Database usage details

    Gives the size occupied by data in this database.

    SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
  27. Find the size of the SCHEMA/USER

    Give the size of user in MBs.

    SELECT SUM (bytes / 1024 / 1024) "size"
      FROM dba_segments
     WHERE owner = '&owner';
  28. Last SQL fired by the User on Database

    This query will display last SQL query fired by each user in this database. Notice how this query display last SQL per each session.

    SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME,
             s.program || '-' || s.terminal || '(' || s.machine || ')' PROG,
             s.sid || '/' || s.serial# sid,
             s.status "Status",
             p.spid,
             sql_text sqltext
        FROM v$sqltext_with_newlines t, V$SESSION s, v$process p
       WHERE     t.address = s.sql_address
             AND p.addr = s.paddr(+)
             AND t.hash_value = s.sql_hash_value
    ORDER BY s.sid, t.piece;

    Performance related queries

  29. CPU usage of the USER

    Displays CPU usage for each User. Useful to understand database load by user.

    SELECT ss.username, se.SID, VALUE / 100 cpu_usage_seconds
        FROM v$session ss, v$sesstat se, v$statname sn
       WHERE     se.STATISTIC# = sn.STATISTIC#
             AND NAME LIKE '%CPU used by this session%'
             AND se.SID = ss.SID
             AND ss.status = 'ACTIVE'
             AND ss.username IS NOT NULL
    ORDER BY VALUE DESC;
  30. Long Query progress in database

    Show the progress of long running queries.

    SELECT a.sid,
             a.serial#,
             b.username,
             opname OPERATION,
             target OBJECT,
             TRUNC (elapsed_seconds, 5) "ET (s)",
             TO_CHAR (start_time, 'HH24:MI:SS') start_time,
             ROUND ( (sofar / totalwork) * 100, 2) "COMPLETE (%)"
        FROM v$session_longops a, v$session b
       WHERE     a.sid = b.sid
             AND b.username NOT IN ('SYS', 'SYSTEM')
             AND totalwork > 0
    ORDER BY elapsed_seconds;
  31. Get current session id, process id, client process id?

    This is for those who wants to do some voodoo magic using process ids and session ids.

    SELECT b.sid,
           b.serial#,
           a.spid processid,
           b.process clientpid
      FROM v$process a, v$session b
     WHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
    • V$SESSION.SID AND V$SESSION.SERIAL# is database process id
    • V$PROCESS.SPID is shadow process id on this database server
    • V$SESSION.PROCESS is client PROCESS ID, ON windows it IS : separated THE FIRST # IS THE PROCESS ID ON THE client AND 2nd one IS THE THREAD id.
  32. Last SQL Fired from particular Schema or Table:

    SELECT CREATED, TIMESTAMP, last_ddl_time
      FROM all_objects
     WHERE     OWNER = 'MYSCHEMA'
           AND OBJECT_TYPE = 'TABLE'
           AND OBJECT_NAME = 'EMPLOYEE_TABLE';
  33. Find Top 10 SQL by reads per execution

    SELECT *
      FROM SELECT ROWNUM,
                     SUBSTR (a.sql_text, 1, 200) sql_text,
                     TRUNC (
                        a.disk_reads / DECODE (a.executions, 0, 1, a.executions))
                        reads_per_execution,
                     a.buffer_gets,
                     a.disk_reads,
                     a.executions,
                     a.sorts,
                     a.address
                FROM v$sqlarea a
            ORDER BY 3 DESC)
     WHERE ROWNUM < 10;
  34. Oracle SQL query over the view that shows actual Oracle connections.

    SELECT osuser,
             username,
             machine,
             program
        FROM v$session
    ORDER BY osuser;
  35. Oracle SQL query that show the opened connections group by the program that opens the connection.

    SELECT program application, COUNT (program) Numero_Sesiones
        FROM v$session
    GROUP BY program
    ORDER BY Numero_Sesiones DESC;
  36. Oracle SQL query that shows Oracle users connected and the sessions number for user

    SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
        FROM v$session
    GROUP BY username
    ORDER BY Numero_Sesiones DESC;
  37. Get number of objects per owner

    SELECT owner, COUNT (owner) number_of_objects
        FROM dba_objects
    GROUP BY owner
    ORDER BY number_of_objects DESC;

    Utility / Math related queries

  38. Convert number to words

    More info: Converting number into words in Oracle

    SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;

    Output:

    one thousand five hundred twenty-six
  39. Find string in package source code

    Below query will search for string ‘FOO_SOMETHING’ in all package source. This query comes handy when you want to find a particular procedure or function call from all the source code.

    --search a string foo_something in package source code
    SELECT *
      FROM dba_source
     WHERE UPPER (text) LIKE '%FOO_SOMETHING%'
    AND owner = 'USER_NAME';
  40. Convert Comma Separated Values into Table

    The query can come quite handy when you have comma separated data string that you need to convert into table so that you can use other SQL queries like IN or NOT IN. Here we are converting ‘AA,BB,CC,DD,EE,FF’ string to table containing AA, BB, CC etc. as each row. Once you have this table you can join it with other table to quickly do some useful stuffs.

    WITH csv
         AS (SELECT 'AA,BB,CC,DD,EE,FF'
                       AS csvdata
               FROM DUAL)
        SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_char
          FROM DUAL, csv
    CONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;
  41. Find the last record from a table

    This ones straight forward. Use this when your table does not have primary key or you cannot be sure if record having max primary key is the latest one.

    SELECT *
      FROM employees
     WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);
     
    (OR)
     
    SELECT * FROM employees
    MINUS
    SELECT *
      FROM employees
     WHERE ROWNUM < (SELECT COUNT (*) FROM employees);
  42. Row Data Multiplication in Oracle

    This query use some tricky math functions to multiply values from each row. Read below article for more details.
    More info: Row Data Multiplication In Oracle

    WITH tbl
         AS (SELECT -2 num FROM DUAL
             UNION
             SELECT -3 num FROM DUAL
             UNION
             SELECT -4 num FROM DUAL),
         sign_val
         AS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END val
               FROM tbl
              WHERE num < 0)
      SELECT EXP (SUM (LN (ABS (num)))) * val
        FROM tbl, sign_val
    GROUP BY val;
  43. Generating Random Data In Oracle

    You might want to generate some random data to quickly insert in table for testing. Below query help you do that. Read this article for more details.
    More info: Random Data in Oracle

    SELECT LEVEL empl_id,
               MOD (ROWNUM, 50000) dept_id,
               TRUNC (DBMS_RANDOM.VALUE (1000, 500000), 2) salary,
               DECODE (ROUND (DBMS_RANDOM.VALUE (1, 2)),  1, 'M',  2, 'F') gender,
               TO_DATE (
                     ROUND (DBMS_RANDOM.VALUE (1, 28))
                  || '-'
                  || ROUND (DBMS_RANDOM.VALUE (1, 12))
                  || '-'
                  || ROUND (DBMS_RANDOM.VALUE (1900, 2010)),
                  'DD-MM-YYYY')
                  dob,
               DBMS_RANDOM.STRING ('x', DBMS_RANDOM.VALUE (20, 50)) address
          FROM DUAL
    CONNECT BY LEVEL < 10000;
  44. Random number generator in Oracle

    Plain old random number generator in Oracle. This ones generate a random number between 0 and 100. Change the multiplier to number that you want to set limit for.

    --generate random number between 0 and 100
    SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;
  45. Check if table contains any data

    This one can be written in multiple ways. You can create count(*) on a table to know number of rows. But this query is more efficient given the fact that we are only interested in knowing if table has any data.

    SELECT 1
      FROM TABLE_NAME
     WHERE ROWNUM = 1;

If you have some cool query that can make life of other Oracle developers easy, do share in comment section.

2015년 2월 24일 화요일

Oracle Query Calendar-1st

OS : Windows 7
DBMS : Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production

One day, suddenly.
I wanted to create a calendar-related programs.
So. Start~

first, DB Query.
SELECT LPAD( MONTH, 20-(20-LENGTH(MONTH))/2 ) MONTH,"Sun", "Mon", "Tue",
 "Wed", "Thu", "Fri", "Sat", week
 FROM (SELECT TO_CHAR(dt,'fmMonthfm YYYY') MONTH,TO_CHAR(dt+1,'iw') week,
 MAX(DECODE(TO_CHAR(dt,'d'),'1',LPAD(TO_CHAR(dt,'fmdd'),2))) "Sun",
 MAX(DECODE(TO_CHAR(dt,'d'),'2',LPAD(TO_CHAR(dt,'fmdd'),2))) "Mon",
 MAX(DECODE(TO_CHAR(dt,'d'),'3',LPAD(TO_CHAR(dt,'fmdd'),2))) "Tue",
 MAX(DECODE(TO_CHAR(dt,'d'),'4',LPAD(TO_CHAR(dt,'fmdd'),2))) "Wed",
 MAX(DECODE(TO_CHAR(dt,'d'),'5',LPAD(TO_CHAR(dt,'fmdd'),2))) "Thu",
 MAX(DECODE(TO_CHAR(dt,'d'),'6',LPAD(TO_CHAR(dt,'fmdd'),2))) "Fri",
 MAX(DECODE(TO_CHAR(dt,'d'),'7',LPAD(TO_CHAR(dt,'fmdd'),2))) "Sat"
 FROM ( SELECT TRUNC(SYSDATE,'y')-1+ROWNUM dt
 FROM all_objects
 WHERE ROWNUM <= ADD_MONTHS(TRUNC(SYSDATE,'y'),12) - TRUNC(SYSDATE,'y'))
 GROUP BY TO_CHAR(dt,'fmMonthfm YYYY'), TO_CHAR( dt+1, 'iw' ))
 ORDER BY TO_DATE( MONTH, 'Month YYYY' ), TO_NUMBER(week);

results :
MONTH                            
--------------------------------
Sun Mon Tue Wed Thu Fri Sat WEEK
--- --- --- --- --- --- --- ----
    January 2015                 
                 1   2   3  01  
                                 
    January 2015                 
 4   5   6   7   8   9  10  02  
 ...
 ...
While studying notes.
1. all_objects : ohhhhh~~~
2. ROWNUM <= ADD_MONTHS(TRUNC(SYSDATE,'y'),12) - TRUNC(SYSDATE,'y') : WOW!
3. TO_CHAR Function : I always forget almost.
um. Ok. next~

now, Change the query to be able to change the year.
SELECT LPAD( MONTH, 20-(20-LENGTH(MONTH))/2 ) MONTH,"Sun", "Mon", "Tue",
 "Wed", "Thu", "Fri", "Sat", week
 FROM (SELECT TO_CHAR(dt,'fmMonthfm YYYY') MONTH,TO_CHAR(dt+1,'iw') week,
 MAX(DECODE(TO_CHAR(dt,'d'),'1',LPAD(TO_CHAR(dt,'fmdd'),2))) "Sun",
 MAX(DECODE(TO_CHAR(dt,'d'),'2',LPAD(TO_CHAR(dt,'fmdd'),2))) "Mon",
 MAX(DECODE(TO_CHAR(dt,'d'),'3',LPAD(TO_CHAR(dt,'fmdd'),2))) "Tue",
 MAX(DECODE(TO_CHAR(dt,'d'),'4',LPAD(TO_CHAR(dt,'fmdd'),2))) "Wed",
 MAX(DECODE(TO_CHAR(dt,'d'),'5',LPAD(TO_CHAR(dt,'fmdd'),2))) "Thu",
 MAX(DECODE(TO_CHAR(dt,'d'),'6',LPAD(TO_CHAR(dt,'fmdd'),2))) "Fri",
 MAX(DECODE(TO_CHAR(dt,'d'),'7',LPAD(TO_CHAR(dt,'fmdd'),2))) "Sat"
 FROM ( SELECT TRUNC(to_date('2015-01-01', 'yyyy-mm-dd'),'y')-1+ROWNUM dt
 FROM all_objects
 WHERE ROWNUM <= ADD_MONTHS(TRUNC(to_date('2015-01-01', 'yyyy-mm-dd'),'y'),12) - TRUNC(to_date('2015-01-01', 'yyyy-mm-dd'),'y'))
 GROUP BY TO_CHAR(dt,'fmMonthfm YYYY'), TO_CHAR( dt+1, 'iw' ))
 ORDER BY TO_DATE( MONTH, 'Month YYYY' ), TO_NUMBER(week);
execute~~~ Ok. work.
Confirmed that.

2015년 2월 23일 월요일

XRTableCell of XRTable format change : string to datetime

OS : Windows 7
IDE : Microsoft Visual Studio Professional 2012
Microsoft .NET Framework 4.5.51209
DeploymentTool : DevExpress 14.1
Form : XtraReport

Date Time
20150223 114322
20150211 212907
20150212 202059

I want to change column format string to datetime.
then, What should I do?

Ok, change cloumn's diplay format.
wasting my time...
Ok, reading devexpress doc.
wasting my time...
Ok, google serching.

I finally got it.
 
        private void xrTblCellDate_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            var varDate = GetCurrentColumnValue((sender as XRTableCell).Tag.ToString());
            if (varDate != null && varDate.ToString() != "")
            {
                string strPattern = "yyyyMMdd";
                DateTime dtDate;
                if (DateTime.TryParseExact(varDate.ToString(), strPattern, null, System.Globalization.DateTimeStyles.None, out dtDate))
                    (sender as XRTableCell).Text = string.Format("{0:yyyy-MM-dd}", dtDate);
            }
        }
        private void xrTblCellTime_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            var varTime = GetCurrentColumnValue((sender as XRTableCell).Tag.ToString());
            if (varTime != null && varTime.ToString() != "")
            {
                string strPattern = "hhmmss";
                TimeSpan dtTime;
                if (TimeSpan.TryParseExact(varTime.ToString(), strPattern, null, System.Globalization.TimeSpanStyles.None, out dtTime))
                    (sender as XRTableCell).Text = string.Format("{0}", dtTime);
            }
        }
Date Time
2015-02-23 11:43:22
2015-02-11 21:29:07
2015-02-12 20:20:59

정보처리기사 필기 2006년 5월 A형 운영체제

<가상 기억장치>

• 보조기억장치(하드디스크)의 일부를 주기억장치처럼 사용하는 것으로, 용량이 작은 주기억장치를 마치 큰 용량을 가진 것처럼 사용하는 것으로, 현재 사용되는 운영체제에서 흔히 사용되는 기법이다.
• 주기억장치의 용량보다 큰 프로그램을 실행하기 위해 사용한다.
• 가상 기억장치에 저장된 프로그램을 실행하려면 가상기억장치의 주소를 주기억장치의 주소로 바꾸는 주소변환 작업(주소 매핑)이 필요하다.
• 블록 단위로 나누어 사용하므로 연속 할당 방식에서 발생할 수 있는 단편화를 해결할 수 있다.
• 기억장치의 이용률과 다중 프로그래밍의 효율을 높일 수 있다.
• 운영체제의 설계가 복잡해지고 주소 변환을 위한 테이블을 사용하므로 기억장소를 낭비할 수 있다.
• 가상 기억장치 구현 기법
 - 페이징 (Paging)기법
 - 세그먼테이션 (Segmentation)기법

<교착 상태(Deadlock)>

 정의
상호 배제에 의해 나타나는 문제점으로, 둘 이상의 프로세스들이 자원을 점유한 상태에서 서로 다른 프로세스가 점유하고 있는 자원을 요구하며 무한정 기다리는 현상
 필요 충분 조건
- 상호 배제(Mutual Exclusion) : 한 번에 한 개의 프로세스만이 공유 자원을 사용할 수 있어야 함
- 점유와 대기(Hold & Wait) : 최소한 하나의 자원을 점유하고 있으면서 다른 프로세스에 할당되어 사용되고 있는 자원을 추가로 점유하기 위해 대기하는 프로세스가 있어야 함
- 비선점(Non-preemptive) : 다른 프로세스에 할당된 자원은 사용이 끝날 때까지 강제로 빼았을 수 없어야 함
- 환형 대기(Circular Wait) : 공유 자원과 공유 자원을 사용하기 위해 대기하는 프로세스들이 원형으로 구성되어 있어 자신에게 할당된 자원을 점유하면서 앞이나 뒤에 있는 프로세스의 자원을 요구해야 함

<UNIX의 주요 명령어>

명령어
의미
fork
새로운 프로세스 생성(하위 프로세스 호출, 프로세스 복제)
exec
새로운 프로세스 수행
&
백그라운드 처리를 위해 명령의 끝에 입력
wait
fork exec 의해 실행되는 프로세스의 상위 프로세스가 하위 프로세스 종료 등의 event 기다림
exit
프로세스 수행 종료
cat
내용을 화면에 표시(DOS 명령 TYPE’과 유사)
chmod
파일의 사용 허가 지정
mount
파일 시스템을 마운팅(새로운 파일 시스템을 기존 파일 시스템의 서브 디렉터리에 연결하는 )
mkls
파일 시스템 생성
chdir
현재 사용할 디렉터리 위치 변경
fsck
파일 시스템을 검사 보수하여 무결성을 검사
rmdir
디렉터리 삭제   
ls
현재 디렉터리 내의 파일 목록 확인
getpid
자신의 프로세스 아이디를 얻음
getppid
부모 프로세스의 아이디를 얻음
cp
파일 복사
mv
파일 이동 이름 변경
rm
파일 삭제
finger
사용자 정보를 표시함

<인터럽트의 종류 및 발생 원인>

 외부 인터럽트
- 전원 이상 인터럽트(Power Fail Interrupt) 
: 정전이 되거나 전원 이상이 있는 경우
• 기계 착오 인터럽트(Machine Check Interrupt) 
CPU의 기능적인 오류 동작이 발생한 경우
• 외부 신호 인터럽트(External Interrupt)
1. 타이머에 의해 규정된 시간(Time Slice)을 알리는 경우
2. 키보드로 인터럽트 키를 누른 경우
3. 외부장치로부터 인터럽트 요청이 있는 경우
• 입·출력 인터럽트(Input-Output Interrupt)
1. 입·출력 Data의 오류나 이상 현상이 발생한 경우
2. 입·출력장치가 데이터의 전송을 요구하거나 전송이 끝났음을 알릴 경우

<국부성(Locality, 구역성)>

• 프로세스가 실행되는 동안 주기억장치를 참조할 때 일부 페이지만 집중적으로 참조하는 성질이 있다는 이론이다.
• 스래싱을 방지하기 위한 워킹 셋 이론의 기반이 된다.
• 프로세스가 집중적으로 사용하는 페이지를 알아내는 방법 중 하나로, 가상 기억장치 관리의 이론적인 근거가 된다.
• Locality 종류
- 시간 구역성 (Temporal Locality)
 1. 프로세스가 실행되면서 하나의 페이지를 일정 시간 동안 집중적으로 액세스하는 현상
 2. 시간 구역성이 이루어지는 기억장소 : Loop(반복, 순환), 스택(Stack), 부프로그램(Sub Routine), Counting(1씩 증감), Totaling(집계)에 사용되는 변수(기억장소)
- 공간 구역성 (Spatial Locality)
 1. 프로세스 실행 시 일정 위치의 페이지를 집중적으로 액세스하는 현상
 2. 공간 구역성이 이루어지는 기억장소 : 배열 순회(Array Traversal), 순차적 코드의 실행,       프로그래머들이 관련된 변수(데이터를 저장할 기억장소)들을 서로 근처에 선언하여 할당되는 기억장소, 같은 영역에 있는 변수를 참조할 때 사용

<선점 스케줄링의 종류>

선점 우선순위
준비상태 큐의 프로세스들 중에서 우선순위가 가장 높은 프로세스에게 먼저 CPU 할당하는 기법
SRT
(Shortest
Remaining
Time)
비선점 기법인 SJF 알고리즘을 선점 형태로 변경한 기법으로, 현재 실행중인 프로세스의 남은 시간과 준비상태 큐에 새로 도착한 프로세스의 실행 시간을 비교하여 가장 짧은 실행 시간을 요구하는 프로세스에게 CPU 할당하는 기법
RR
(Round Robin)
시분할 시스템(Time Sharing System) 위해 고안된 방식으로, FCFS 알고리즘을 선점 형태로 변형한 기법
FCFS(FIFO) 기법과 같이 준비상태 큐에 먼저 들어온 프로세스가 먼저 CPU 할당받지만 각 프로세스는 할당된 시간(T i m e S l i c e, Quantum) 동안만 실행한 실행이 완료되지 않으면 다음 프로세스에게 CPU 넘겨주고 준비상태 큐의 가장 뒤로 배치됨
할당되는 시간이 경우 FCFS 기법과 같아지고, 할당되는 시간이 작을 경우 문맥 교환 및 오버헤드가 자주 발생됨
다단계 (Multi
level Queue)
프로세스를 특정 그룹으로 분류할 있을 경우 그룹에 따라 각기 다른 준비상태 큐를 사용하는 기법
다단계 피드백
(Multi level
Feedback
Queue)
특정 그룹의 준비상태 큐에 들어간 프로세스가 다른 준비상태 큐로 이동할 없는 다단계 큐 기법을 준비상태 사이를 이동할 있도록 개선한 기법

<스래싱(Thrashing)>

• 프로세스의 처리 시간보다 페이지 교체 시간이 더 많아지는 현상이다.
• 다중 프로그래밍 시스템이나 가상 기억장치를 사용하는 시스템에서 하나의 프로세스 수행 과정중 자주 페이지 부재가 발생함으로 인해 나타나는 현상으로 전체 시스템의 성능이 저하된다.
• 다중 프로그래밍의 정도가 높아짐에 따라 CPU의 이용률은 어느 특정 시점까지는 높아지지만 다중 프로그래밍의 정도가 더욱 커지면 스래싱이 나타나고, CPU의 이용률은 급격히 감소된다.
• CPU 이용률을 높이고, 스래싱 현상을 방지하려면 다중 프로그래밍의 정도를 적정 수준으로 유지, 부족한 자원 증설, 일부 프로세스 중단, 페이지 부재 빈도 (Page Fault Frequency) 조절, Working Set 유지, 적정 프레임 수 제공 등의 방법을 수행한다.

<직접 파일(Direct File), 직접 접근방식>

• 파일을 구성하는 레코드를 임의의 물리적 저장공간에 기록하는 것이다.
• 레코드에 특정 기준으로 키가 할당되며, 해싱 함수 (Hashing Function)를 이용하여 이 키에 대한 보조기억장치의 물리적 상대 레코드 주소를 계산한 후 해당하는 주소에 레코드를 저장한다.
• 레코드는 해싱 함수에 의해 계산된 물리적 주소를 통해 직접 접근이 가능하다.
• 임의 접근이 가능한 자기 디스크나 자기 드럼을 사용한다.
• 장점 : 파일의 각 레코드에 직접 접근하거나 기록할 수 있음, 접근 시간이 빠르고, 레코드의 삽입, 삭제, 갱신이 용이함
• 단점 : 레코드의 주소 변환 과정이 필요하며, 이 과정으로 인해 시간이 소요됨, 기억공간의 효율이 저하됨, 기억장치의 물리적 구조에 대한 지식이 필요함

<FIFO 페이지 부재수 구하기>

• 예시
FIFO 교체 알고리즘을 사용하고 페이지 참조의 순서가 다음과 같다고 가정한다면 할당된 프레임의 수가 4개일 때 몇 번의 페이지 부재가 발생하는가? (단, 초기 프레임은 모두 비어 있다고 가정한다.)
0  1  2  3  0  1  4  0  1  2  3  4

• 해결
[ ][ ][ ][ ]
[0][ ][ ][ ] - 부재
[0][1][ ][ ] - 부재
[0][1][2][ ] - 부재
[0][1][2][3] - 부재
[0][1][2][3] - hit (0 1 2 3 다음에 0인데 프레임안에 이미 있기때문에 hit입니다.)
[0][1][2][3] - hit (마찬가지로 1도 프레임 안에 있으므로 hit)
[4][1][2][3] - 부재 (4를 입력해야하는데 프레임 안에 없으므로. 부재. 0이 제일 먼저 들어왔었으므로 0을제거하고 4입력)
[4][0][2][3] - 부재 (0을 입력해야하는데 프레임 안에 없으므로. 부재. [4][1][2][3]중에 제일 먼저 있었던놈인 1을 제거하고 0입력)
[4][0][1][3] - 부재 (1을 입력해야하는데 프레임 안에 없으므로. 부재. [4][0][2][3]중에 제일 먼저있던놈인 2제거후 1입력)
[4][0][1][2] - 부재 (2를 입력해야하는데 프레임 안에 없으므로. 부재. 알아서 하실거라고 봐요)
[3][0][1][2] - 부재 (3을 입력해야하는데 프레임 안에 없으므로. 부재.)
[3][4][1][2] - 부재

• 결론
10 page faults.

• etc. Belady’s Anomaly

<디스크 스케줄링>

• 사용할 데이터가 디스크 상의 여러 곳에 저장되어 있을 경우 데이터를 액세스하기 위해 디스크 헤드가 움직이는 경로를 결정하는 기법이다.
• 디스크 스케줄링의 목적 : 처리량 최대화, 평균 응답 시간의 최소화, 응답 시간 편차의 최소화

<비선점 스케줄링의 종류>

FCFS
(First-Come
First-Service)
준비상태 큐에 도착한 순서에 따라 차례로 CPU 할당하는 기법
먼저 도착한 것이 먼저 처리되어 공평성은 유지되지만 짧은 작업이 작업을, 중요한 작업이 중요하지 않은 작업을 기다리게
SJF
(Shortest Job
First)
실행 시간이 가장 짧은 프로세스에 먼저 CPU를 할당하는 기법
가장 적은 평균 대기 시간을 제공하는 최적 알고리즘
HRN(Hightest
Responseratio
Next)
실행 시간이 프로세스에 불리한 SJF 기법을 보완하기 위한 것으로, 대기 시간과 서비스(실행)시간을 이용하는 기법
우선순위 계산 공식 =
(대기 시간 + 서비스 시간) / 서비스 시간
우선 순위 계산 결과값이 높은 것부터 우선 순위가 부여되는데, 대기 시간이 프로세스일 경우 계산 결과값이 높게 나옴
기한부
(Deadline)
프로세스에게 일정한 시간을 주어 시간 안에 프로세스를 완료하도록 하는 기법
시스템은 프로세스에게 할당할 정확한 시간을
추정해야 하며, 이를 위해서 사용자는 시스템이
요구한 프로세스에 대한 정확한 정보를 제공해
우선순위
(Priority)
준비상태 큐에서 기다리는 프로세스마다 우선순위를 부여하여 가장 높은 프로세스에게 먼저 CPU 할당하는 기법

대항해시대 조선 랭작

숙련도 획득 방법 선박 건조, 선박 강화, 전용함 추가시 숙련도 획득 모두 동일한 공식 적용 획득 숙련도 공식 기본 획득 숙련도 ≒ int{건조일수 × 현재랭크 × (0.525)} 이벤트 & 아이템 사용...