Daemon Processes

of 25/25
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
  • date post

  • Category


  • view

  • download


Embed Size (px)


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. Daemon Processes. Coding rules (see page 425) Call umask and set the file mode creation mask to 0 Call fork and let the parent die - PowerPoint PPT Presentation

Transcript of Daemon Processes

  • Daemon ProcessesLong lived utility processesOften started at system boot and ended when system shuts downRun in the background with no controlling terminal

  • Daemon ProcessesCoding rules (see page 425)Call umask and set the file mode creation mask to 0Call fork and let the parent dieCall setsidChange current working directory to root directoryClose unneeded file descriptors

  • Advanced I/ONonblocking I/OI/O MultiplexingThe poll() function callThe select() function callFile record lockingMemory mapped I/O

  • Slow I/OReads of certain file types that can block forever if data is not ready (pipes, terminal devices, network devices)Writes on those same file types where data cant be accepted immediately (pipe full, network flow control, etc)Opens of certain file types that block until some condition becomes true (terminal device that waits on a modem, open of a FIFO for writing only when no other process has it open for reading)

  • Slow I/OReads and writes of files with mandatory record locking enabledSome ioctl operationsSome IPC functions

  • Nonblocking I/OWe can specify nonblocking I/O when we open a file by providing the O_NONBLOCK flag open(file,O_RDONLY | O_NONBLOCK);If the file is already open, we can use fcntl to set the O_NONBLOCK flag

  • Nonblocking I/Oflags = fcntl(fd, F_GETFL, 0);flags = flags | O_NONBLOCK;fcntl(fd, F_SETFL, flags);F_GETFL get flagsF_SETFL set flagsCheck if file has nonblocking I/O enabled if(flags & O_NONBLOCK)Turn off nonblocking I/O flags = flags & ~O_NONBLOCK; fcntl(fd, F_SETFL, flags);

  • I/O MultiplexingAvoids the busy waiting loop common with simple nonblocking I/OUsing multiplexing we can block on multiple file descriptors simultaneously

  • poll functionint poll(struct pollfd *fds, nfds_t nfds, int timeout);struct pollfd { int fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */};fds is an array of pollfd elementsnfds is the number of elements in the arraytimeout specifies how long the function should blocktimeout = 0 dont blocktimeout = -1 - wait forevertimeout > 0 - wait timeout miliseconds

  • select functionint select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */};timeout specifies how long to blockNULL wait forever, or until a signal is caughttv_sec = 0 and tv_usec = 0 dont blocktv_sec != 0 or tv_usec != 0 block until a descriptor is ready or the timeout is reached. Can also be interrupted by a signal

  • select functionreadfds, writefds, exceptfds are pointers to descriptor sets telling the system which file descriptors we are interested in for reading, writing and exceptionsThe type for descriptor sets is fd_set. This type can not be directly manipulatedUse the following functions with fd_setvoid FD_CLR(int fd, fd_set *set);int FD_ISSET(int fd, fd_set *set);void FD_SET(int fd, fd_set *set);void FD_ZERO(fd_set *set);nfds is the number of file descriptors (usually the highest number plus one)

  • Scatter Read and Gather Writessize_t readv(int fd, const struct iovec *vector, int count);ssize_t writev(int fd, const struct iovec *vector, int count);struct iovec { void *iov_base; /* Starting address */ size_t iov_len; /* Number of bytes */};readv and writev allows us to read or write to multiple non contiguous buffers at the same timefd is the file descriptor to read from or write tovector is a pointer to an array of iovec structurescount is the number of elements in the array

  • Memory Mapped I/OReading/Writing a memory address actually causes I/O to another deviceFunctions are provided to memory map an open file

  • Memory Mapped I/Ovoid *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);Maps an open file to an area of memorystart lets us request a given starting point in memory. length is the number of bytes to read from the file

  • Memory Mapped I/Ooffset is the location within the file to beginfd is the file descriptor to be mappedprot specifies the protection of the mapped regionPROT_READ - region can be readPROT_WRITE region can be writtenPROT_EXEC region can be executedPROT_NONE region cannot be accessedflags sets attributes of the mapped region. See page 488 for values and descriptions

  • Memory Mapped I/Oint munmap(void *start, size_t length);A mapped region is automatically unmapped when the process terminatesmunmap can be used to unmap a region earlierstart beginning address of mapped regionlength number of bytes in regionNote: closing the file descriptors does not unmap a region.

  • File (Record) LockingAllows a process to lock a portion of a file to prevent access by another processAdvisory LockingA convention that all processes accessing the file must followMandatory LockingEnforced by the Kernel. Other processes suspended if they try to read/write the locked sectionMandatory Locking enabled by turning on the Set Group ID bit and turning off the group execute bit

  • File (Record) LockingLocking Functionslockf - System Vflock BSDfcntl - POSIX

  • fcntl Record Lockingint fcntl(int fd, int cmd, struct flock *lock);struct flock { short l_type; short l_whence; off_t l_start; off_t l_len; pid_t l_pid; };fd an open file descriptor

  • fcntl Record Lockinglock a pointer to a flock structl_type F_RDLCK, F_WRLCK or F_UNLCKl_start starting byte offset of locked regionl_whence same as for lseek: SEEK_SET, SEEK_CUR, SEEK_ENDl_len length in bytes to lock. 0 means lock until EOFl_pid used to return a pid with F_GETLK

  • fcntl Record LockingcmdF_GETLK checks to see if we can acquire the requested lock. If another process has a conflicting lock the information about that lock is passed back through lockF_SETLK set a lockF_SETLKW set a lock, but wait if there is a conflict. May be interrupted by a signal

  • fcntl Record LockingLock type must be consistent with the opened mode of the fileF_RDLCK for O_RDONLY or O_RDWRF_WRLCK for O_WRONLY or O_RDWR

  • Lock CompatibilityAny number of processes may have shared read locks on a region of a fileOnly one processes at a time can have an exclusive write lock on a regionWe can not obtain a write lock on a region that already has a read lockWe can not obtain a read lock on a region that already has a write lock

  • Lock CombiningIf a process attempts to acquire a lock on a region it already has a lock on the old lock is replaced by the new lockThe system will split and combine locks automaticallyLock acquired from byte 100 to 200Lock released for bytes 125 to 150We now have 2 locks for bytes 100 to 125 and 150 to 200

  • Implied Inheritance and Release of LocksLocks are associated with a process and a fileIf the process terminates, its locks are releasedWhen a file is closed, any locks on it for that process are releasedLocks are not inherited across a forkLocks are inherited across an exec unless the close-on-exec flag is set


    Call umask processes may have inherited a file creation mask, but may want to set permissions on new files explicitly. Set umask to zero to avoid interference with newly created file permissions.

    fork This is a preparation step for calling the setsid function. Remember that a processes group leader can not become the leader of a new session. Forking and letting the parent die assures us that the child is not the processes group leader

    setsid causes the processes (the child from the step above) to become a new session leader, processes group leader and will break any connection to a controlling terminal

    chdir to / - We want to be sure that the daemon is not running on a file system that may need to be unmounted later. **

    I/O divided into slow and everything else. The slow functions may block forever***

    Using nonblocking I/O calls can lead to polling I/O which wastes valuable CPU time**

    events can be one of:

    POLLIN data ready to be readPOLLOUT writing now will not be blockedPOLLPRI - urgent data is available for reading

    See page 480 for full list of events

    poll returns the number of ready file descriptors, 0 on timeout and -1 on errorRequires

    poll function comes from System V*

    select function requires

    Returns the number of ready descriptors, 0 on timeout, -1 on error*

    The functions for modifying the fd_set also require

    Select function comes from BSD*Requires **


    The start parameter is only a request and may not be honored. We can pass in the value zero if we dont care where the region begins. The actual starting location is returned by the function if ok, or MAP_FAILED on error. *

    Note that prot can not give us more permissions than we had when we opened the file. For example, if we opened the file read only, then we cannot map it as PROT_WRITE*

    Note also that unmapping does not flush the mapped region. We can use the msync(void *addr, size_t len, int flags) function to force a flush of the mapped region*********

    Closing a file can cause an interesting situation. Suppose we have 2 file descriptors open for a file that has locks associated with it. If either of them are closed, the locks will be released for both because the locks are associated with the file, not the file descriptors!