CIS 415

Unix Processes

ß PID ( ID) - unique number used to identify each process

Unix Process Management ß Process creation system calls ß Process destruction kill

2

Unix fork system call Unix fork system call

ß (creator, old process) ß BEFORE fork ß (created, new process) Printf(“one\n”); ß After fork, two processes exist and are running concurrently. Pid = fork(); Printf(“two\n”);

ß fork causes a new process to be created with Process A a duplicate of the parent’s code ß AFTER fork ß fork returns a value of 0 to the child. Printf(“one\n”); Printf(“one\n”); ß fork returns the child’s PID to the parent Pid = fork(); Pid = fork(); ß (greater than 0) Printf(“two\n”); Printf(“two\n”); 3 4 Parent process A Child process B

Unix fork system call Unix exec system call

/* new process using fork */ ß Replaces old process with new code. main() { ß After exec, the process is running a new pid_t pid; piece of code. printf(“Just one process so far\n”); printf(“Calling fork\n”); ß Process ID is the same. pid = fork(); /* create new process */ ß exec never returns except if error. if (pid == 0) ß exec provides a means for passing printf(“I am the child\n”); parameters from the old to the new. else if (pid > 0) printf(“I am the parent; my child has pid %d\n”, ß Family of exec system calls differ in where pid); the code comes from and how parameters are else passed. printf(“fork returned error code, no child\n”); } 5 6

Interrupts 1 CIS 415

Unix exec system call Unix process creation

•int main( void ) { ß BEFORE exec • • pid_t pid; /* type is from sys/types.h */ Printf(“hello\n”); • int error_code; • pid = fork(); Pid = execl(“bin/ls”); Printf(“never\n”); • if( pid == 0 ) { This code never executed. • printf( "\nI am the child, running %s.\n" • , program_name ); Process A • ß AFTER exec • /* never returns if all goes well */ Code for ls • error_code • = execl(“/bin/program_name”, • , “program_name”, • , "-l", (char*)0 ); • printf( "Error running ls, execl returned %d.",error_code ); Process B (Note that Process A no longer exists.)7 • (0); 8 • }

Unix process creation (cont) Unix process id system calls

•else {

• printf( "\nI am the parent process.\n"); • getpid - returns the pid of this process • printf("My child is pid:%d\n", (long)pid ); • getppid - returns pid of this process’ parent • exit(0); • } •}

9 10

Unix process monitoring Unix process monitoring

The Unix ps command (process status) The Unix time command (process execution stats) time Allows user to query status of processes. Unix will display information such as: Unix will display the following timing information: process ID, parent process ID user system elapsed % priority, memory mgmt info, runtime Where user is CPU time in user code system is CPU time in kernel code elapsed is total time in system % is percentage of elapsed time that is CPU time

11 12

Interrupts 2