TDC368 UNIX and Network Programming Camelia Zlatea, PhD Week 6:  Inter-Process Synchronization  Signals.

Slides:



Advertisements
Similar presentations
Inter-Process Communication: Message Passing Tore Larsen Slides by T. Plagemann, Pål Halvorsen, Kai Li, and Andrew S. Tanenbaum.
Advertisements

©2009 Operačné systémy Procesy. 3.2 ©2009 Operačné systémy Process in Memory.
Unix programming Term: III B.Tech II semester Unit-V II PPT Slides Text Books: (1)unix the ultimate guide by Sumitabha Das (2)Advanced programming.
NCHU System & Network Lab Lab 15 Record Locking. NCHU System & Network Lab Record Locking (1/4) What happens when two process attempt to edit the same.
Daemon Processes Long lived utility processes Often started at system boot and ended when system shuts down Run in the background with no controlling terminal.
Zombie and orphan processes. Zombie process (from wikipedia) When a process ends, all of the memory and resources associated with it are deallocated.
4.1 Operating Systems Lecture 11 UNIX Pipes Read Handout "An Introduction to Concurrency..."
CS 311 – Lecture 09 Outline Introduction to Systems programming – System calls – Categories of system calls Error Management System calls File Handling.
Concurrency: Deadlock and Starvation Chapter 6. Revision Describe three necessary conditions for deadlock Which condition is the result of the three necessary.
Rings This chapter demonstrates how processes can be formed into a ring using pipes for communication purposes.
Exec function Exec function: - replaces the current process (its code, data, stack & heap segments) with a new program - the new program starts executing.
TDC368 UNIX and Network Programming
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Process Control in Unix Operating Systems Hebrew University Spring 2004.
CS Lecture 16 Outline Inter-process Communication (IPC) – Pipes – Signals Lecture 161CS Operating Systems 1.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
TDC561 Network Programming Camelia Zlatea, PhD Review UNIX Architecture and Programming.
Today’s topic Inter-process communication with pipes.
Unix Processes Slides are based upon IBM technical library, Speaking Unix, Part 8: Unix processes Extended System Programming Laboratory (ESPL) CS Department.
1 Concurrency: Deadlock and Starvation Chapter 6.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Processes Tarek Abdelzaher Vikram Adve.
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.
Adv. UNIX: lowIO/161 Advanced UNIX v Objectives –look at low-level operations for handling files Special Topics in Comp. Eng. 2 Semester.
Inter-Process Communication Mechanisms CSE331 Operating Systems Design.
Unix Pipes Pipe sets up communication channel between two (related) processes. 37 Two processes connected by a pipe.
Fundamentals CIS 552. Fundamentals Low-level I/O (read/write using system calls)  Opening/Creating files  Reading & Writing files  Moving around in.
CS 3214 Computer Systems Lecture 13 Godmar Back.
CSC Advanced Unix Programming, Fall, 2008 Welcome back to UNIX System Programming! Monday, September 15, class 4.
Cli/Serv.: procs/51 Client/Server Distributed Systems v Objectives –look at how to program UNIX processes , Semester 1, Processes.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
System V IPC Provides three mechanisms for InterProcess Communication (IPC) : Messages : exchange messages with any process or server. Semaphores : allow.
Shell (Part 2). Example r What if we want to support something like this: m ps –le | sort r One process should execute ps –le and another should execute.
System Commands and Interprocess Communication. chroot int chroot(const char *path); chroot changes the root directory to that specified in path. This.
4061 Session 23 (4/10). Today Reader/Writer Locks and Semaphores Lock Files.
Pipes A pipe is a simple, synchronized way of passing information between processes A pipe is a special file/buffer that stores a limited amount of data.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 8: Opening Files and Starting Processes.
CS162B: Pipes Jacob T. Chan. Pipes  These allow output of one process to be the input of another process  One of the oldest and most basic forms of.
Chapter 71 Deadlock Detection revisited. Chapter 72 Message Passing (see Section 4.5 in Processes Chapter)  A general method used for interprocess communication.
IPC Programming. Process Model Processes can be organized into a parent-child hierarchy. Consider the following example code: /* */
Operating Systems Process Creation
CS4315A. Berrached:CMS:UHD1 Process Management Chapter 6.
Process Synchronization Azzam Mourad COEN 346.
CSCI 330 UNIX and Network Programming Unit XII: Process & Pipe Part 1.
Recitation 11 (Nov. 22) Outline Lab 6: interposition test Error handling I/O practice problem Reminders Lab 6: Due Tuesday Minglong Shao
Recitation: Signaling S04, Recitation, Section A Debug Multiple Processes using GDB Debug Multiple Processes using GDB Dup2 Dup2 Signaling Signaling.
Laface 2007 File system 2.1 Operating System Design Filesystem system calls buffer allocation algorithms getblk brelse bread breada bwrite iget iput bmap.
Pipes Pipes are an inter-process communication mechanism that allow two or more processes to send information to each other.
Interprocess Communication
Interprocess Communication. Resource Sharing –Kernel: Data structures, Buffers –Processes: Shared Memory, Files Synchronization Methods –Kernel: Wait.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Tarek Abdelzaher Vikram Adve CS241 Systems Programming System Calls and I/O.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
OS interface: file and I/O system calls File operations in C/C++? –fopen(), fread(), fwrite(), fclose(), fseek() in C f.open(…), f.close(…) in C++ I/O.
Dsh: A Devil Shell COMPSCI210 Recitation 14 Sep 2012 Vamsi Thummala.
Dup, dup2 An existing file descriptor ( filedes ) is duplicated The new file descriptor returned by dup is guaranteed to be the lowest numered available.
4.1 Operating Systems Lecture 9 Fork and Exec Read Ch
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
Using System Calls (Unix) Have to tell compiler (if C/C++) where to find the headers, etc. – i.e., the “include” files May have to tell compiler where.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Pipes and Fifos.
FILE LOCK #include <stdio.h> #include <stdlib.h>
Tarek Abdelzaher Vikram Adve Marco Caccamo
CS 3733 Operating Systems Topics: IPC and Unix Special Files
Pipes A pipe provides a one-way flow of data example: who | sort| lpr
LINUX System Programming with Processes (additional)
2/25/08 Frans Kaashoek MIT OS abstractions 2/25/08 Frans Kaashoek MIT
Unix System Calls and Posix Threads
File I/O (1) Prof. Ikjun Yeom TA – Mugyo
IPC Prof. Ikjun Yeom TA – Hoyoun
Chapter 3: Process Concept
System Programming: Process Management
Presentation transcript:

TDC368 UNIX and Network Programming Camelia Zlatea, PhD Week 6:  Inter-Process Synchronization  Signals  Lock-Files

UNIX Network Programming – TDC Page 2 Spring 2003 Discussion  File Redirectation  Inter-process Communication via pipe –Pipe synchronization –Deadlock? »A deadlock situation can occur when two processes open respectively the two ends of a pipe for writing –Starvation? »Blocking reader / writer for unbounded interval of time –Errors »“Broken Pipe”? SIGPIPE –Process Type »Related process(named or unamed pipes) »Unrelated process (only named pipes)  Pipe vs. File for inter-process communication?

UNIX Network Programming – TDC Page 3 Spring 2003 I/O redirection - ex: sort result #include int main(void) { int fd1, fd2; switch (fork()) { case -1: perror("fork"); break; case 0: if ((fd1 = open("test.dat", O_RDONLY))==1) || (fd2 = open("results", O_WRONLY|O_CREAT|O_TRUNC,0644))==-1) { perror("open failure"); _exit(errno); } /* set standard input from "test.dat" */ if (dup2(fd1,0)==-1) _exit(errno); /* set standard output to "results" */ if (dup2(fd2,1)==-1) _exit(errno); close(fd1); close(fd2); execl("sort","sort"); perror("execl"); exit(errno); } return 0; }

UNIX Network Programming – TDC Page 4 Spring 2003 Simulating sleep by using alarm and pause #include void wakeup() { ; }; unsigned int sleep ( unsigned int timer ) { if (sigset(SIGALRM, wakeup)==-1) { perror("sigset"); return 1; } (void)alarm( timer ); (void)pause(); return 0; }

UNIX Network Programming – TDC Page 5 Spring 2003 Example: A Producer-Consumer relation int main(void) { int fd, n, i; pid_t pid, ppid; char buf[1]; if((fd=open("/tmp/data_file", O_APPEND|O_CREATE, 0640)) <0) exit(1); sigset(SIGTERM,SIG_IGN);/* signal */ ; sigset(SIGINT,SIG_IGN); /* signal */ pid=fork(); switch (pid) { case -1: { perror(“FORK”); exit(1); } case 0: /* child process - Producer */ sigset(SIGUSR1,wakeup); sighold(SIGUSR1); /* block / hold signals SIGUSR1 until sigpause*/ for (i=0; i<=100; i++) { /* sleep a random amount of time */ n = (int)(getpid()%256); srand((unsigned)n); sleep(rand() %5); /* writes a character in file */ sprintf(buf,"%d",i); write(fd, buf,sizeof(buf)); fprintf(stderr,"Producer PID=%d value = %d\n",getpid(), i); ppid=getppid(); kill(ppid, SIGUSR2); sigpause(SIGUSR1);/* pause(); until SIGUSR! received*/ } break; void wakeup() { ; };

UNIX Network Programming – TDC Page 6 Spring 2003 Example: A Producer-Consumer relation default: /* -parent code - Consumer */ sigset(SIGUSR2,wakeup); sighold(SIGUSR2); /* block / hold signals SIGUSR2 until sigpause*/ for (i=0; i<=100; i++) { /* sleep a random amount of time */ n = (int)(getpid()%256); srand((unsigned)n); sleep(rand() %5); sigpause(SIGUSR2); /* pause(); */ /* reads a character from file */ read(fd, buf,sizeof(buf)); fprintf(stderr,"Consumer PID=%d value=%d\n",getpid(),atoi(buf)); kill(pid, SIGUSR1) } break; } exit(0); }

UNIX Network Programming – TDC Page 7 Spring 2003  Provide a mechanism to share data among processes  Provide a mechanism to synchronize reading and writing of shared files.  Applicable for regular files  A process imposes a lock on a file(or record) so that other processes can’t modify the file(record) until it is unlocked by the process. UNIX File/Record Locking

UNIX Network Programming – TDC Page 8 Spring 2003 UNIX File/Record Locking  write lock –exclusive lock –processes are prevented from setting any overlapping read/write locks on the locked region of the file  read lock –shared lock –processes are prevented from setting any overlapping write locks on the locked region of the file

UNIX Network Programming – TDC Page 9 Spring 2003  mandatory lock –enforced by OS kernel –example: chmod a+l file_name  an erroneous situation: A process sets a mandatory lock on a file and never unlocks it. The file cannot be accessed by any other process until the owner process is either killed or system is re-booted UNIX File/Record Locking

UNIX Network Programming – TDC Page 10 Spring 2003  advisory lock –processes can still use read or write to access the shared file unless cooperation procedure is followed  processes using advisory locks to share a file must cooperate: –try to set a lock on the record to be accessed (read or write) –if fails to set the lock then: »wait and test_again or »do_work and test_again –if succeeds to set the lock »accesses the locked file/record »releases the lock UNIX File/Record Locking

UNIX Network Programming – TDC Page 11 Spring 2003 System V 4 and POSIX.1 #include int fcntl(int fd, int cmd,struct flock fl); cmd: –F_SETLK »sets a file lock; »do not block if failure –F_SETLKW »sets a file lock »blocks until succeeds –F_GETLK »tests if a file or record is locked and by whom UNIX File/Record Locking

UNIX Network Programming – TDC Page 12 Spring 2003 System V 4 and POSIX.1 struct flock { shortl_type; /* lock type */ shortl+whence; /* rec. ref. */ off_tl_start; /* rec. offset */ off_tl_len; /* rec.length */ pid_tl_pid; /* process ID*/ }; UNIX File/Record Locking

UNIX Network Programming – TDC Page 13 Spring 2003 System V 4 and POSIX.1 /* lock type */ F_RDLCK - read/shared lock F_WRLCK - write/exclusive lock F_UNLCK - unlock a record/file /* record reference */ SEEK_CUR - current file pointer SEEK_SET - byte 0 of file SEEK_END - EOF UNIX File/Record Locking

UNIX Network Programming – TDC Page 14 Spring 2003 Simulating Semaphores with Lock Files int Pflag(char *file_name, int ntries, int nsec) { int fd; i=0; while ((fd = create(file_name,0)) ==-1 && errno ==EACCES) /* EACCES - file exists, no write permission on it */ if (++i <ntries) sleep(nsec); else return 0; close(fd); /* lock_file created with 0 bytes and no permissions */ if (fd == -1) return 0; else return 1; }

UNIX Network Programming – TDC Page 15 Spring 2003 Simulating Semaphores with Lock Files int Vflag(char *file_name) { int i; i = unlink(file_name); if (i==0) return 1; /* success, lock file removed */ if (i==-1) return 0; /* failure, lock file was not removed */ }

UNIX Network Programming – TDC Page 16 Spring 2003 Process Synchronizations using Lock Files int main(void) { pid_t p; int i; q, status, nbytes; int fd; char buf[80]; /* parent process opens date file Shared Data File */ if ((fd = open("/tmp/data_file", O_RDONLY|O_CREATE, 0666))<0) { perror("open"); exit(1); } /* parent forks 3 new processes */ for (i=0; i<4; i++) { if (p=fork()) == 0) break; } switch (p) { case 0:/* a child process */ if (Pflag("/tmp/lock_file", 5,10)) { if (nbytes=read(fd,buf,sizeof(buf)))>0) { fprintf(stderr,"PID=%d data=%s\n", getpid(), buf); sleep(10); /* releases the resource - shared file */ Vflag("/tmp/lock_file"); } else fprintf(stderr, "Cannot access data file\n"); break;

UNIX Network Programming – TDC Page 17 Spring 2003 Process Synchronizations using Lock Files case -1:/* cannot fork processes */ perror("fork"); exit(1); break; default:/* parent */ while ((q=wait(&status))>0) ; break; } exit(0); }