150 likes | 285 Views
Introduction to UNIX 2. Ke Liu http://www.cs.binghamton.edu/~kliu/cs350/ Kliu1@binghamton.edu. Last Time. SSH, Login and Log out Shells and Shell commands man, ls, cd, pwd, mkdir, rmdir, rm, cp, mv, chmod, ps, kill File System: /, directory, file, pathname Editors C Compiler: gcc
E N D
Introduction to UNIX 2 Ke Liu http://www.cs.binghamton.edu/~kliu/cs350/ Kliu1@binghamton.edu
Last Time • SSH, Login and Log out • Shells and Shell commands man, ls, cd, pwd, mkdir, rmdir, rm, cp, mv, chmod, ps, kill • File System: /, directory, file, pathname • Editors • C Compiler: gcc • Foreground / Background Processes
Process Control • 3 primary functions: • fork( ) • exec( ) • wait( )
Fork( ) • The only way of creating a new process in Unix. • New process is called “child process”. • Fork returns twice !! • Once in the parent returning the child process ID. • Once in child returning 0.
Fork example 1 #include <sys/types.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 main( ) 5 { 6 int pid; 7 pid = fork( );
Fork example 8 if(pid = = 0) 9 printf(“Hello from the child\n"); 10 while(1); 11 else 12 printf("This is parent\n"); 13 }
Fork example bingsun2% gcc –o hello hello.c or gcc hello.c –o hello bingsun2% test Hello from the child Hello from the parent • What about files opened in parent?
Exec( ) • Executes commands. • Normally, the parent process does a fork( ), creates a child and the child process does an exec( ) • exec( ) never returns if successful !! • 6 different ways.
Exec( ) example • execvp call 1 #include <sys/types.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 main() 5 { 6 int pid; 7 char * command[2];
Exec( ) example 8 command[0] = (char*)malloc(10); 9 command[1] = (char*)malloc(10); 10 strcpy(command[0], "ls"); 11 strcpy(command[1], "-l"); 12 command[2] = (char*)0; 13 pid = fork(); 14 if(pid == 0) 15 { 16 printf("This is child\n");
Exec( ) example 17 execvp(*command, command); 18 } 19 else 20 printf("This is parent\n"); 21 }
Wait( ) • Wait for a process to terminate. • Generally used in parent process which waits for the child to terminate • waitpid( ) waits for a specific process. • Example programs for wait()
Inter-process communication. • Signals: software interrupts generated when certain asynchronous events occur. • E.g.: when you press Control C to stop a program. • Pipes.
Inter-process communication. • Semaphores: mutual exclusion. • Shared memory: multiple processes share a common region in memory. • Message queues: linked-list of messages.
Debugging • An easy way to debug in my opinion is printf statements. • GDB: Gnu Debugger. Help for gdb available on class homepage • Invest some time learning it; it will make your life much easier • http://www.gnu.org/manual/gdb/