Lab 3. 프로세스 생성과 종료 (Unix/Linux) One, Two 출력하는 onetwo.c 코딩, 컴파일, 실행

Slides:



Advertisements
Similar presentations
1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
Advertisements

1 Introduction to UNIX 2 Ke Liu
1 Processes and Pipes COS 217 Professor Jennifer Rexford.
Exec function Exec function: - replaces the current process (its code, data, stack & heap segments) with a new program - the new program starts executing.
CS Lecture 15 Outline Process Management System calls – exec() – chdir() – system() – nice() – Accessing User and Group IDs – Redirection Lecture.
Process Control in Unix Operating Systems Hebrew University Spring 2004.
Process in Unix, Linux and Windows CS-3013 C-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
CS-502 Fall 2006Processes in Unix, Linux, & Windows 1 Processes in Unix, Linux, and Windows CS502 Operating Systems.
Unix & Windows Processes 1 CS502 Spring 2006 Unix/Windows Processes.
Fork and Exec Unix Model Tutorial 3. Process Management Model The Unix process management model is split into two distinct operations : 1. The creation.
Processes in Unix, Linux, and Windows CS-502 Fall Processes in Unix, Linux, and Windows CS502 Operating Systems (Slides include materials from Operating.
Outline Unix Architecture Vi Fork Pthread. UNIX Architecture.
Process. Process Concept Process – a program in execution Textbook uses the terms job and process almost interchangeably A process includes: – program.
Some Example C Programs. These programs show how to use the exec function.
The Programming Interface. Main Points Creating and managing processes – fork, exec, wait Performing I/O – open, read, write, close Communicating between.
Shell (Part 1). Process r A process is an instance of an application running r If there are two instances of an application running then there are two.
Process in Unix, Linux, and Windows CS-3013 A-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
Exercise #2: Process Creation/Termination and Interprocess Communication J. H. Wang Mar. 30, 2010.
Today’s Topics Introducing process: the basic mechanism for concurrent programming –Process management related system calls Process creation Process termination.
Linux/UNIX Programming APUE (Introduction) 문양세 강원대학교 IT 대학 컴퓨터과학전공.
Process. Processes A process is an abstraction for sequence of operations that implement a computation/program. A process may be manipulated, suspended,
1 Week 2 The Crunchy Shell to the Soft and Chewy Kernel… Sarah Diesburg 8/3/2010 COP4610 / CGS5765.
Creating and Executing Processes
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 8: Opening Files and Starting Processes.
ITEC 502 컴퓨터 시스템 및 실습 Chapter 2-1: Process Mi-Jung Choi DPNM Lab. Dept. of CSE, POSTECH.
Introduction to UNIX Road Map: 1. UNIX Structure 2. Components of UNIX 3. Process Structure 4. Shell & Utility Programs 5. Using Files & Directories 6.
CS 241 Section Week #2 9/9/10. 2 Topics This Section MP1 issues MP2 overview Process creation using fork()‏ Debugging tools: valgrind, gdb.
CS 153 Design of Operating Systems Spring 2015 Lecture 5: Processes and Threads.
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
Process Management CS3320 Spring Process A process is an instance of a running program. –Not the same as “program” or “processor” Process provides.
Operating Systems Process Creation
CS4315A. Berrached:CMS:UHD1 Process Management Chapter 6.
What is a Process? u A process is an executable “cradle” in which a program may run u This “cradle” provides an environment in which the program can run,
Fall 2002 CS 325 Class Notes Page 1 Lecture 25 Today –exec() in Unix –CreateProcess in Windows Announcements.
CSCI 330 UNIX and Network Programming Unit XII: Process & Pipe Part 1.
Process Management Azzam Mourad COEN 346.
1 A Seven-State Process Model. 2 CPU Switch From Process to Process Silberschatz, Galvin, and Gagne  1999.
CSCI 330 UNIX and Network Programming
CS431-cotter1 Linux Programming, Processes, and Threads Man pages (fork, clone, execve, pthread_create) The Linux Programming Interface – Kerrisk, No Starch,
The Process CIS 370, Fall 2009 CIS UMassD. The notion of a process In UNIX a process is an instance of a program in execution A job or a task Each process.
Tutorial 3. In this tutorial we’ll see Fork() and Exec() system calls.
OPERATING SYSTEMS 3 - PROCESSES PIETER HARTEL 1. Principle of concurrency - giving a process the illusion that it owns the whole machine  A process has:
2.1 Processes  process = abstraction of a running program  multiprogramming = CPU switches from running program to running program  pseudoparallelism.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
Slide 1 COMP 3438 System Programming UNIX Processes UNIX Processes (Chapters 2 & 3)
1 Unix system calls fork( ) wait( ) exit( ). 2 How To Create New Processes? n Underlying mechanism -A process runs fork to create a child process -Parent.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
4.1 Operating Systems Lecture 9 Fork and Exec Read Ch
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
C 프로그래밍 개발 도구. 컴파일러 gnu c compiler 컴파일 gcc sample.c 실행 a.out 실행 파일 지정 컴파일 gcc –o sample sample.c 실행 sample.
1 Intro to the Shell with Fork, Exec, Wait Sarah Diesburg Operating Systems CS 3430.
Chapter 3 The Programming Interface Chien-Chung Shen CIS/UD
A process is a program in execution A running system consists of multiple processes – OS processes Processes started by the OS to do “system things” –
CSCI 4061 Recitation 2 1.
Processes in Unix, Linux, and Windows
Processes in Unix, Linux, and Windows
More on UART Interrupts; System Calls
Fork and Exec Unix Model
LINUX System Programming with Processes (additional)
Processes in Unix, Linux, and Windows
2.1 Processes process = abstraction of a running program
Process Creation Process Termination
Tutorial 3 Tutorial 3.
Process Programming Interface
Tutorial: The Programming Interface
Processes in Unix, Linux, and Windows
Processes in Unix and Windows
EECE.4810/EECE.5730 Operating Systems
EECE.4810/EECE.5730 Operating Systems
Presentation transcript:

Lab 3. 프로세스 생성과 종료 (Unix/Linux) One, Two 출력하는 onetwo.c 코딩, 컴파일, 실행 (Unix/Linux) fork 예제 forkvalue.c 코딩, 컴파일, 실행 (Unix/Linux) 시스템 호출 execl()을 이용하여 ls 프로그램을 실행시키는 forkexecl.c 코딩, 컴파일, 실행 (Unix/Linux) 시스템 호출 execv()를 이용하여 ls 프로그램을 실행시키는 forkexecv.c 코딩, 컴파일, 실행 (Unix/Linux) Shell을 느끼는 background.c 코드 분석, 컴파일, 실행 (Unix/Linux) mystatus.c & myexit.c 코드 분석, 컴파일, 실행 (Windows) Win32 API를 이용한 새 프로세스 생성 (교재 p108) 코딩, 컴파일, 실행 1~6번만 제출 (집에서도 접속 가능합니다) 2 Electronic versions: multi.incheon.ac.kr (117.16.244.53)의 지정 디렉토리 /export/home/os2011hwa 또는 os2011hwb 에 자기 학번의 디렉토리 만들고 그 곳에 소스파일과 실행파일 복사 mylinux.incheon.ac.kr (117.16.244.59) 지정 디렉토리 /home/os2011hwa 또는 os2011hwb 에 자기 학번의 디렉토리 만들고 그 곳에 소스파일과 실행파일 복사 운영체제

1. fork 시스템 호출 printf(“One\n”); pid = fork(); printf(Two\n”); #include <stdio.h> main() { int pid; printf("One\n"); pid = fork(); printf("Two\n"); } printf(“One\n”); pid = fork(); printf(Two\n”); PC A $ gcc onetwo.c –o onetwo BEFORE fork AFTER printf(“One\n”); pid=fork(); printf(“Two\n”); printf(“One\n”); pid = fork(); printf(“Two\n”); PC PC A B 운영체제

fork와 exec호출의 조합 pid = fork(); wait((int*)0); execl(“/bin/ls” …); PC A BEFORE FORK AFTER FORK wait((int*)0); execl(“/bin/ls” …); PC PC A B AFTER FORK AFTER EXEC wait((int*)0); /* first line of ls */ PC PC A B (now runs ls) 운영체제

2. fork()로 새 프로세스를 생성하는 C program #include <stdio.h> #include <stdlib.h> #include <unistd.h> void main(int argc, char *argv[]) { int pid; /* fork another process */ pid = fork(); if(pid < 0) { /* error occurred */ fprintf(stderr, “Fork Failed”); exit(-1); } else if (pid == 0) { /* child process */ execl(“/bin/ls”, “ls”, “-l”, NULL); } else { /* parent process */ wait(NULL); printf(“Child Complete\n”); exit(0); } execv char *av[3]; av[0]=“ls”; av[1]=“-l”; av[2]=(char *)0; execv(“/bin/ls”, av); execlp, execvp 쉘 환경변수 PATH를 따름 execlp(“ls”, “ls”, “-l”, (char *)0); execvp(“ls”, av); 운영체제

4. fork() + exec() example: background.c 후면처리 (background processing) 실행 $ gcc background.c –o background $ ./background ls -l 코드 $ cat background.c #include <stdio.h> main (argc, argv) int argc; char* argv []; { if (fork () == 0) /* Child */ execvp (argv[1], &argv[1]); /* Execute other program */ fprintf (stderr, "Could not execute %s\n", argv[1]); } 운영체제

5. exit example: mystatus.c & myexit.c $ cat mystatus.c #include <stdio.h> main () { int pid, status, childPid; printf ("I'm the parent process and my PID is %d\n", getpid ()); pid = fork (); /* Duplicate */ if (pid != 0) /* Branch based on return value from fork () */ printf ("I'm the parent process with PID %d and PPID %d\n", getpid (), getppid ()); childPid = wait (&status); /* Wait for a child to terminate. */ printf ("A child with PID %d, terminated with exit code low: %d, high: %d\n“, childPid, (status & 0xFF), status >> 8); /* Linux */ } else printf ("I'm the child process with PID %d and PPID %d\n", // execl ("/bin/ls", "ls", "-li", (char *)0); execl ("/export/home/mysung/osprog/myexit", "myexit", (char *)0); exit (42); /* Exit with a silly number */ printf ("PID %d terminates\n", getpid () ); $ cat myexit.c #include <stdio.h> main () { printf ("I'm going to exit with return code 77\n"); exit (77); } 운영체제

6. Win32 API를 이용한 새 프로세스 생성 #include <windows.h> #include <stdio.h> int main( VOID ) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Start the child process. if( !CreateProcess( NULL, // No module name (use command line). "C:\\WINDOWS\\system32\\mspaint.exe", // Command line. NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. 0, // No creation flags. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi ) // Pointer to PROCESS_INFORMATION structure. ) CloseHandle( pi.hThread );; handles.FINITE );etLastError() ); } 운영체제

(C언어 보충) Command-line Arguments $ gcc myecho.c –o myecho $ ./myecho hello world! Output hello world! argc 와 argv[] argc=3 argv[0]: “echo” argv[1]: “hello” argv[2]: “world” Source code $ cat myecho.c #include <stdio.h> main(int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) printf(“%s%s”, argv[i], (i < argc-1) ? “ “ : “”); printf(“\n”); return 0; } argv: myecho\0 hello\0 world\0 운영체제

(C언어 보충) argv 처리: optional flag myecho2.c (숫자 option 처리) $ cat myecho2.c #include <stdio.h> main(int argc, char *argv[]) { int i; for(i=1; i<argc; i++) printf("%s%s", argv[i], (i<argc-1)? " “ : ""); if(argv[i][0] == '-') printf(“ (제곱값은 %d) ", (atoi(argv[i]))*(atoi(argv[i]))); } printf("\n"); return 0; 운영체제

(C언어 보충) argv 처리: optional flag myfind -n -x pattern $ cat myfind.c #include <stdio.h> #include <string.h> #define MAXLINE 1000 int getline(char *line, int max); /*find : print lines that match pattern from 1st arg */ main(int argc, char *argv[]) { char line[MAXLINE]; long lineno = 0; int c, except =0, number =0, found =0; while(--argc > 0 && (*++argv)[0] == '-') while(c = *++argv[0]) switch(c) { case 'x': except = 1; break; case 'n': number = 1; default: printf("find : illegal optin %c\n",c); argc = 0; found = -1; } if(argc != 1) printf("Usage : find -x -n patttern\n"); else while(getline(line, MAXLINE) > 0) { lineno++; if((strstr(line, *argv) != NULL ) != except) { if(number) printf("%ld:", lineno); printf("%s\n", line); found++; } return found; int getline(char s[], int lim) { int c, i; for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = '\0'; ++i; return i; 운영체제

Linux/Unix C 언어 프로그래밍 cc compiler man cc $ cc –o hello hello.c $ hello gcc compiler GNU project C and C++ Compiler GNU(GNU’s Not Unix, Free Software Foundation의 Richard Stallman) man gcc info gcc $ gcc hello.c $ a.out $ gcc –o hello hello.c 운영체제

유닉스 디버거 : gdb 프로그램을 기호적으로 디버깅 : dbx, adb, sdb, gdb, ddd(Motif) 등 단일단계이동(single stepping) 정지점(breakpoint) 디버거 내에서 편집 변수의 접근 및 수정 함수의 탐색 추적(tracing) gdb GNU debugger, 별도의 프롬프트 표시 관련정보는, 프롬프트에서 help를 입력 dbx executableFilename 디버그를 위한 프로그램 준비 cc의 -g 옵션으로 프로그램을 번역 ⇒ 목적 모듈 내에 디버깅 정보 포함 운영체제

유닉스 디버거 : gdb gdb 실행 gdb 실행 파일이름 : 실행 파일을 디버그함 (실행 파일은 반드시 -g 옵션을 사용하여 컴파일되어야 함) gdb 명령어  b (breakpoint) : 실행 중 디버그를 위해 멈추는 위치 지정 b 함수명 : 함수명에서 멈춤 b 라인번호 : 라인번호에서 멈춤 r (run) : 실행 시작 n (next) : 현재 라인 실행 (함수의 경우 실행하고 다음 라인으로 넘어 감) s (step) : 현재 라인 실행 (함수의 경우 호출된 함수 내로 들어가 실행 계속) c (continue) : 다음 breakpoint까지 실행 l (list) : 현재 수행되고 있는 라인부터 10개 라인씩 연속적으로 소스 코드를 프린트 p (print) 변수명 : 변수명으로 저장되어 있는 내용을 프린트 h (help) : 도움말 q (quit) : gdb 종료  운영체제

$ Vi 편집 모드 ~ ~ Vi mode (Vi 명령 모드) x r dd a i esc oO R $Vi filename :q! (기록 않음) ZZ(기록) :wq a i esc x r dd 커서이동 append insert oO open R replace 운영체제

Vi를 이용한 기본 텍스트 편집 텍스트의 삭제 및 취소(undo) x(exclude?) d(delete) dw db d$ d^ r(replace) u(update) U(Update) 최근 명령 재 실행 . 파일 관리 Vi를 벗어나지 않고 저장하기: :w 저장 않고 끝내기: :q! 또 다른 파일 편집: :e xx 또는 :e! xx 다른 파일을 읽어 와 덧붙이기: :r xx http://marvel.inchon.ac.kr/ 의 Information 참조 커서의 이동 hjkl 이용 H J K L  [Vi mode] 4j G 명령으로 원하는 행으로 이동 7G G : 마지막 행으로 화면 이동 ^F ^B ^D ^U 텍스트 추가, 삽입, 수정 a(append) i(insert) o(open) O(Open) R(Replace) 운영체제