20
[Unix Programming] [Unix Programming] Process Basic Process Basic Young-Ju, Han Young-Ju, Han Email: Email: [email protected]

[Unix Programming] Process Basic

  • Upload
    dixie

  • View
    55

  • Download
    0

Embed Size (px)

DESCRIPTION

[Unix Programming] Process Basic. Young-Ju, Han Email: [email protected]. Contents. Introduction main Function Process Termination Command-line Arguments Environment List Memory Layout of a C Program. main Function (1). The prototype of the main function. - PowerPoint PPT Presentation

Citation preview

Page 1: [Unix Programming] Process Basic

[Unix Programming][Unix Programming]Process BasicProcess Basic

Young-Ju, HanYoung-Ju, Han

Email: Email: [email protected]

Page 2: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 22

ContentsContents

Introduction main Function Process Termination Command-line Arguments Environment List Memory Layout of a C Program

Page 3: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 33

main Function (1)main Function (1)

The prototype of the main function.int main(int argc, char *argv[]);

You did make only main(), but there are some more code in a.out C start-up code : doing initializations for the process and

call

exit(main(argc, argv));

C start-up code

Doing initialization ;exit( main(argc,argv)) ;

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

… return 0 ;

}

a.out

Page 4: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 44

main Function (2)main Function (2)

How a C Program starts. You enter “a.out” on the shell

prompt $ a.out

Shell forks itself and duplicates itself

The duplicated shell calls exec(“a.out”)

The duplicated shell is replaced with “a.out”

“a.out” runs

Shell :$ a.out

Shell Shell

fork

a.out

exec

Page 5: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 55

Process Termination (1)Process Termination (1)

Process terminations Normal

Return from main Calling exit Calling _exit

Abnormal calling abort terminated by a signal

main() {printf(“hello, world\n”);exit( 0 );

}

int main( void ) {printf(“hello, world\n”);return 0 ;

}

main() {printf(“hello, world\n”);_exit( 0 );

}

Page 6: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 66

Process Termination (2)Process Termination (2)

exit #include <stdlib.h> void exit(int status); C library function Perform certain cleanups and return to the kernel closing all open file descriptors calling of all exit handlers (clean-up actions)

_exit #include <unistd.h> void _exit(int status); System call Return to the kernel immediately

Page 7: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 77

Process Termination (3)Process Termination (3)

Prototype of atexit() function

ANSI C 에서 exit 에 의해 자동으로 call 되는 function 을 32 개까지 등록할 수 있음 ( 즉 , exit handlers)

등록한 역순으로 call 됨 등록한 횟수만큼 call 됨

#include <stdlib.h>

int atexit( void (*func) (void));

returns: 0 if OK, nonzero on error

Page 8: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 88

Process Termination (4)Process Termination (4)

Example of atexit()

#inlcude <stdlib.h>#include <stdio.h>static void my_exit1(void), my_exit2(void) ;

int main( void ) {atexit( my_exit2 ) ;atexit( my_exit1 ) ;atexit( my_exit1 );printf( "main is done\n" ) ;return 0 ;

}

static void my_exit1( void ) { printf( "first exist handler\n" ) ; }static void my_exit2( void ) { printf( "second exist handler\n" ) ; }

$ a.outmain is donefirst exit handlerfirst exit handlersecond exit handler$

Page 9: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 99

Process Termination (5)Process Termination (5)

kernel

exit function

user functions

main function

C start-up routine

exit handler

exit handler

standard I/O cleanup

(via fclose)

...

_exit

exec

call

callreturn

return

exit

exit

exit

call

return

_exit

user process

Page 10: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1010

Command-Line argumentsCommand-Line arguments

The command-line arguments passed to the main function via

two parameters int argc and char *argv[].

Example.

int main(int argc, char *argv[])

{

int i;

printf("argc = %d\n", argc);

for(i=0; i<argc; i++)

printf("argv[%d] = %s\n",

i, argv[i]);

return 0;

}

$ a.out hello world

argc = 3

argv[0] = a.out

argv[1] = hello

argv[2] = world

argc 3

argv

\0

a.out\0

hello\0

world\0

Page 11: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1111

Environment Lists(1)Environment Lists(1)

environment a collection of null-terminated strings

represented a null-terminated array of character pointers

name=value \ 0

int main(int argc, char *argv[], char *envp[]){ while(*envp) printf(“%s\n”, *envp++); return 0;}

HOME=/usr/home/kmjshPATH=:/bin:/usr:/usr/includeSHELL=/bin/sh

Page 12: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1212

Environment Lists(2)Environment Lists(2)

A global variable extern char **environ Example

POSIX.1은 main의 third argument대신에 environ 사용을 권함 특정 environment variable에 접근하기 위해서는 getenv, putenv를 사용

HOME=/home/stevens\0

PATH=:/bin:/usr/bin\0

SHELL=/bin/sh\0

environ

\0 USER=stevens\0

#include <stdio.h> extern char **environ ;

main(){

int i ;for( i = 0 ; environ[i] ; i++ )

printf( "%s\n", environ[i] ) ;}

Page 13: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1313

Environment Lists(3)Environment Lists(3)

getenv To get environment lists

putenv To set environment lists

int main(){ printf(“PATH=%s\n”, getenv(“PATH”)); if ( putenv(“NEW=val”) != 0 ) exit(1); printf(“NEW=%s\n”, getenv(“NEW”)); return 0;}

#include <stdlib.h>

char * getenv(const char *name); int putenv(char* string);

String format“NAME=VALUE\0”Ex) “PATH=:/bin:/usr:/usr/include”

0 :successNon-zero : fail (ENOMEM)

Value pointer : successNULL : not present

Page 14: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1414

Environment Lists(4)Environment Lists(4)

#include <stdlib.h>

int setenv(const char *name, const char* value, int rewrite);

0 : not changedNon-zero : changed

0 :success-1 : fail

#include <stdlib.h>

void unsetenv (const char *name);

setenv name 이 존재하지 않으면 value 로 설정 , 존재하고 rewrite 가

0 이면 갱신하지 않고 , 0 이 아니면 갱신

unsetenv name variable 를 삭제

Page 15: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1515

Memory Layout of a C Program (1)Memory Layout of a C Program (1) Memories 영역들

text: CPU에 의해 수행되는 machine instructions

data: initialized global and static variables.예 ) int maxcount = 99;

bss: uninitialized global and static variables. exec에 의해 0 or null로 초기화 예 ) long sum[1000];

stack: automatic (local) and temporary variables of each

function. 프로그램 실행 중 할당된다 . 함수의 처음에 할당되고 끝나면 소멸된다 .

heap: dynamically allocated area. (malloc, calloc)

Page 16: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1616

stack

heap

Memory Layout of a C Program (2)Memory Layout of a C Program (2)

low address

High address

Initialized to 0by exec

read from program file by exec

Command-line arg& environ. Var.

uninitialized data(bss)

initialized data

text

$ size /usr/bin/cc /bin/sh

text data bss dec hex filename

7205 284 428 7917 1eed /usr/bin/grep

87678 2778 11172 101628 18cfc /bin/sh

Page 17: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1717

Memory Layout of a C Program (3)Memory Layout of a C Program (3)

func(char *str) { char buf[16]; …. strcpy(buf, str); …. } main(int argc, char *argv[]) { …. func(argv[1]) …. }

buf[16]

SFP

RET

argv[1]

main 변수

SFP

RET

Local variable

Stack frame pointer

Return address

argument

low address

high address

Stack structure

Page 18: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1818

Memory Layout of a C Program (4)Memory Layout of a C Program (4)

3 types of memory allocation functions malloc

allocate a specific number of bytes of memory calloc

allocate space for a specified number of objects of a specified size

The space is initialized to all 0 bits realloc

Change the size of a previously allocated area (increase, decrease)

Prototypes.#include <stdlib.h>void *malloc(size_t size);void *calloc(size_t nobj, size_t size);void *realloc(void *ptr, size_t newsize);void free(void *ptr);// 할당된 메모리를 다시 시스템에

반환할때

Page 19: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 1919

Memory Layout of a C Program (5)Memory Layout of a C Program (5)

Global 변수 프로그램의 어디서나 접근 가능한 변수 , <extern> Data 영역 또는 BSS 에 할당

Local 변수 Function 내부에서 정의된 변수

Function 내에서 선언된 Static 변수 Stack 이 아닌 Data 영역 또는 BSS 에 할당되고 , Function

이 call 과 return 에 상관없이 항상 하나만이 존재

Function 밖에서 선언된 Static 변수 Data 영역 또는 BSS 에 할당되며 , File 내에서는 접근 가능

Page 20: [Unix Programming] Process Basic

2007 UNIX Programming2007 UNIX Programming 2020

Memory Layout of a C Program (6)Memory Layout of a C Program (6)

Look at this code: can you differentiate these?int g_i ;int gi_i = 100 ;

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

int l_i ;char *ptr = malloc( 100 ) ;

}

$ size a.out text data bss dec hex filename 28198 9368 500 38066 94b2 a.out

Can you tell me which variable will be allocated into which area?

How can I know the size of each area ?