Unix Full Notes
Unix Full Notes
POSIX Standards
POSIX.1 :
Committee proposes a stdandard for base operating system
APIs
This stadndard is formally known as the IEEE standard
1003.1-1990.
This standard specifies the APIs for the file manipulation
and processes(for Process Creation and Control).
POSIX.1b:
Committee proposes a stdandard for real time operating
system APIs
This stadndard is formally known as the IEEE standard
1003.4-1993
This standard specifies the APIs for the interprocess
communication(Semaphores,Message Passing Shared
Memory).
POSIX.1c:
Committee proposes a stdandard for multithreaded
programming interface
This standard specifies the APIs for Thread Creation,
Control, and Cleanup, Thread Scheduling ,Thread Synchronization and
for Signal Handling .
#define _ POSIX_SOURCE or
#define _POSIX_SOURCE
#define _POSIX_C_SOURCE 199309L
#include <iostream.h>
#include <unistd.h>
int main( )
{
....
}
Context Switching
When the APIs execution completes, the user process is switched back to
the user mode. This context switching for each API call ensures that
process access kernels data in a controlled manner and minimizes any
chance of a runway user application may damage an entire system. So in
general calling an APIs is more time consuming than calling a user
function due to the context switching. Thus for those time critical
applications, user should call their system APIs only if it is necessary.
Most system calls return a special value to indicate that they have failed.
The special value is typically -1, a null pointer, or a constant such as EOF
that is defined for that purpose.
To find out what kind of error it was, you need to look at the error code
stored in the variable errno. This variable is declared in the header file
errno.h as shown below.
volatile int errno
o The variable errno contains the system error number.
void perror (const char *message)
o The function perror is declared in stdio.h.
Errors Meaning
EPERM API was aborted because the calling process does not have the super user
privilege.
EINTR An APIs execution was aborted due to signal interruption.
EIO An Input/Output error occurred in an APIs execution.
ENOEXEC A process could not execute program via one of the Exec API.
EBADF An API was called with an invalid file descriptor.
ECHILD A process does not have any child process which it can wait on.
EAGAIN An API was aborted because some system resource it is requested was
temporarily unavailable. The API should call again later.
ENOMEM An API was aborted because it could not allocate dynamic memory.
EACCESS The process does not have enough privilege to perform the operation.
EFAULT A pointer points to an invalid address.
EPIPE An API attempted to write data to a pipe which has no reader.
ENOENT An invalid file name was specified to an API.
• Regular files Example: All .exe files, C, C++, PDF Document files.
• Directory files Example: Folders in Windows.
• Device files
1. Hard Links
It is a UNIX path or file name, by default files are having only one hard
link
2. Symbolic Links
Symbolic links are called soft links. Soft link are created in the same
manner as hard links, but it requires –s option to the ln command.
Symbolic links are just like shortcuts in windows.
Differences between Hard links and Symbolic Links
UNIX Kernel supports for file / Kernel Data structure for file manipulation
• If open call succeeds, kernel establish the path between preprocess table to
inode table through file table
Step 2:The kernel scan the file table in its kernel space to find an unused entry that can
be assigned to reference the file.
The process’s file table entry will be set to point to this file table entry.
o The file table entry will be set to point to the inode table entry where the
inode record of the file is stored.
o The file table entry will contain the current file pointer of the open file.
o The file table entry will contain open mode that specifies that the file is
open for read-only, write-only or read-write etc.
o The reference count in the file table entry is set to 1. The reference count
keeps track of how many file descriptors from any process are referencing
the entry.
o The reference count of the in-memory inode of the file is increased by 1.
This count specifies how many file table entries are pointing to that inode.
If either step1 or step2 fails, the open function will return with a -1 failure status,
no file descriptor table or file table entry will be allocated.
The figure shows a process’s file descriptor table, the kernel file table and the
inode after the process has opened three files: abc for read only, and xyz for read- write
and xyz again for write only.
r abc
rc=1r rc=
w 1rc
Process Space
rc=1 =2
w xyz
rc=1
Kernel Space
rc = Reference Count
r = Read only
RITM w = Write only -7- Yogish . H. K.
rw= Read Write Figure: Data Structure of File Manipulation
Unix Systems Programming 6TH Semister
The reference count of an allocated file table entry is usually 1, but a process may
When a process calls the function close to close an opened file, the following
sequence of events will occur.
1) The kernel sets the corresponding file descriptor table entry to be unused.
2) It decrements the reference count in the corresponding file table entry by 1. If the
reference count is still non-zero, go to step 6.
3) The file table entry is marked as unused.
4) The reference count in the corresponding file inode table entry is set decremented
by one. If the count is still non-zero go to step 6.
5) If the hard link count of the inode is not zero, it returns to the caller with a success
status otherwise, it marks the inode table entry as unused and de- allocates all the
physical disk storage of the file.
6) It returns to the caller to the process with 0 (success) statuses.
PARAMETERS: path: [in] the path of the new file to create or open.
permission: [in] the new permission mask of the file. It is
masked by the umask value: mode &
~umask.
access_mode: [in] access_mode are explained below.
DESCRIPTION: open opens a file. The access_mode parameter must be one of the
following:
The following values may be or'ed together with one of above access_mode flags:
The permission, argument is required only if the O_CREAT flag is set in the
access_mode argument. It specifies the permissions of owner, group and others.
read
The read function reads a fixed size block of data from to a file referenced by a
given file descriptor.
RETURN VALUE: On the number of bytes read/write at end of file. On error, -1.
3. close
The function close closes the file descriptor filedes. Closing a file
has the following consequences:
RETURN VALUE: On success, the call returns the new file offset where the next read
or write operation will occur. On errror, it returns -1.
5. link : Used for creating alternative file name for existing file
PARAMETERS: oldname: [in] points the file we want to add a link to.
newname: [in] points to the path for the new link.
7. fstat, stat and lstat :These are the functions used to retrieve the attributes of a
given file.
DESCRIPTION: Those calls return a stat structure in buf with the following
format:
struct stat
{
dev_t st_dev; /* device */
ino_t st_ino; /* inode */
umode_t st_mode; /* access mode */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* uid */
gid_t st_gid; /* gid */
dev_t st_rdev; /* device type */
off_t st_size; /* size (in bytes) */
unsigned long st_blksize; /* block size */
unsigned long st_blocks; /* number of allocated blocks */
time_t st_atime; /* last access time */
time_t st_mtime; /* last modification time */
time_t st_ctime; /* last change time */
};
RETURN VALUE: The return value is 0 if the access is permitted and 1 otherwise. (In
other words, treated as a predicate function, access
returns true if the requested access is denied.)
9. chmod and fchmod : The chmod and fchmod functions change file access
permissions for owner, group and others, as well as
the set-UID, set-GID and sticky flags.
PROTOTYPE :
#include <unistd.h>
#include <sys/types.h>
struct utimbuf {
time_t actime; /* access time */
time_t modtime; /* modification time */
}
If *times is NULL, the file's modification time is set to the current time.
12. fcntl : This function is used to query or set access control flags and
close_on_exec flag of any file descriptor. It can also be used to
duplicates the file descriptors and used for file or record locking.
• F_DUPFD : Duplicates filedes the new file descriptor specified by arg. If arg
specifies a file descriptor that was already opened, then the
file descriptor is first closed. It has the same effect has
dup2.
• F_GETFD : Returns the close-on-exec flag of filedes.
• F_SETFD : Sets the close-on-exec flag of filedes.
• F_GETFL : Returns the file descriptor access_mode (as specified by open).
• F_SETFL : Sets the file descriptor access_mode to arg. The only access_mode
that can be modified are O_APPEND and O_NONBLOCK.
• F_GETLK: Determine if the lock described by arg can be set on the file. If so,
the l_type member is set to F_UNLCK. Otherwise, arg is
modified to describe the lock preventing the set operation.
• F_SETLK : Set the lock described by arg on the file or releases an already
existing lock.
• F_SETLKW: Same as F_SETLK but block if the lock can not be set.
struct flock
{
short l_type; /* read, write or unlock */
short l_whence; /* how to interpret l_start */
off_t l_start; /* where to begin the locking area */
off_t l_len; /* the lenght of the area to lock */
The system merges adjacent locking regions of the same type and owned by the
same task. When a sub region inside a region is unlocked, the region is split in two parts.
RETURN VALUE : On success, it depends on the cmd parameter:
DESCRIPTION : Creates a new directory. The uid of the new directory is the
same as the effective uid of the calling task. The gid of the
new directory is the same as its parent directory.
16. mknod This is the API is used for creating Device files.
PROTOTYPE :
#include <sys/stat.h>
#include <unistd.h>
For example: Create a block device file called SCS15 with major and minor
numbers are 15 and 3 respectively, and access permissions of read-write-execute for
everyone, the mknod call is:
17. FIFO: A FIFO ("First In, First Out", pronounced "Fy-Foh") is sometimes known
as a named pipe.
PROTOTYPE :
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
Example: Create a FIFO file called FIFO5 with access permissions of read-write-execute
for everyone, the mkfifo call is:
mkfifo(“FIFO5”,S_IFIFO|S_IRWXU|S_IRWXG|S_IRWXO);
Processes
Process
Process Termination
Normal Termination
2. Abnormal Termination
i. Calling abort
ii. Terminated by a signal
Environment List
The getenv function returns a string that is the value of the environment variable
name.
The putenv function adds or removes definitions from the environment. If the
string is of the form `name=value', the definition is added to the environment.
Otherwise, the string is interpreted as the name of an environment variable, and
any definition for this variable in the environment is removed.
The setenv function can be used to add a new definition to the environment. The
entry with the name name is replaced by the value `name=value'. If the
environment already contains an entry with key name the replace parameter
controls the action. If replace is zero, nothing happens. Otherwise the old entry is
replaced by the new one.
• Text Segment:
• Heap Segment : Dynamic memory allocation takes place in this section only.
1. malloc : Allocate a block of size bytes ,and returns a pointer to the first
byte. The initial value of the memory is indeterminate.
3. realloc : This function changes the size of a block of memory tht was
previously allocated by malloc or by calloc to larger or
smaller, possibly by copying it to a new location.
alloca function
Prototype:
#include <stdlib.h>
#include <sys/resource.h>
struct rlimit
struct rlimit
{
rlim_t rlim_cur; // soft limit : current limit
rlim_t rlim_max ; // hard limit: maximum limit
value for rlim_cur
};
• A soft limit can be changed by any process to a value less than or equal
to its hard limit.
• Any process can lower its hard limit to a value greater than or equal to its
soft limit value. This lowering of the hard limit is irreversible for normal
users.
• Only a super user process can raise a hard limit value.
setjmp function records a location where the future goto will (via the
longjmp call) will return.
#include <unistd.h>
#include <sys/types.h>
Never know whether the parent or child will start executing first.
All file descriptors that are open in the parent are duplicated in the child.
Parent/child also share the same file offset (Files opened after fork() are not
shared).
A process has been terminated, but is still in the operating systems process table
waiting for its parent process to retrieve its exit status.
This is created when child terminates before the parent and parent would not able
to fetch terminated status.
#include <sys/wait.h>
#include <sys/types.h>
The resource information includes the amount of use CPU time, the amount of
system CPU time, number of page faults, number of signals received.
#include <unistd.h>
#include <sys/types.h>
int main( )
{
TELL_WAIT(); //set things up for TELL_xxx and WAIT_xxx
system()
Process Accounting
kernel writes an accounting record each time a process terminates
These accounting records are 32 bytes of binary data
which contains the name of the command, amount of CPU time used, the
user ID , group user ID, starting time and so on.
accton command enables and disables process accounting.
The data required for the accounting record are all kept by the kernel in
the process table and initialized whenever a new process is created (e.g., in
the child after a fork).
Each accounting record is written when the process terminates. This
means that the order of the records in the accounting file corresponds to
the termination order of the processes.
The accounting records correspond to processes, not programs. A new
record is initialized by the kernel for the child after a fork, not when a new
program is execed.
Terminal Logins
Network Logins
In this case all the logins come through the kernel's network interface drivers
(e.g., the Ethernet driver), and we do not know ahead of time how many of these will
occur. Instead of having a process waiting for each possible login, we now have to wait
for a network connection request to arrive. If there is a single process that waits for most
network connections, the inetd process, sometimes called the Internet server.
Process Groups
#include <sys/types.h>
#include <unistd.h>
pid_t getpgrp(void);
Each process group can have a process group leader. The leader is
identified by having its process group ID equal its process ID.
Sessions
A session is a collection of one or more process groups
A process establishes a new session by calling the setsid function.
#include <sys/types.h>
#include <unistd.h>
pid_t setsid(void);
1. The process becomes the session leader of this new session. (A session
leader is the process. That creates a session.) The process is the only
process in this new session.
2. The process becomes the process group leader of a new process group.
The new Process group ID is the process ID of the calling process.
3. This function also makes the calling process have no controlling terminal.
Session
Figure: Arrangement of processes into process group and sessions.
Controlling Terminal
Job Control
Job control allows us to start multiple jobs (group of processes) from a single terminal
and control which jobs can access the terminal and which jobs are to run in the
background. Job control requires three form of support.
The terminal driver in the kernel and signal must support job control
o The terminal driver really looks for three special characters, which
generate signals to the foreground process group:
a. Only the foreground job receives terminal input. When background job
to try to read from the terminal, kernel generates: SIGTTIN signal this is send to
the background process. This normally stops the background job.
Figure: Summary of job control features with foreground and background jobs and
terminal driver.
The solid lines through the terminal driver box mean that the terminal I/O and the ter-
minal generated signals are always connected from the foreground process group to
the actual terminal.
The dashed line corresponding to the SIGTTOU signal means that whether the output
from a process in the background process group appears on the terminal is an option.
Signals
o A signal is a software interrupt delivered to a process.
o These are triggered by event
Events Process
1. Process (Synchronization )
Signal Actions
2. Unix Kernel (Divide by 0) to be
3. User (Ctrl-c ) taken
Signals are defined as integer flags, and they are defined in the header file
<signal.h>. The table below lists the commonly used in POSIX and in UNIX systems.
Signal Core File
Description generated
at default
SIGABRT Abort process Execution. Can be generated by abort( ) API. Yes
SIGALRM Alarm timer time-outs. Can be generated by alarm() API. No
SIGFPE Illegal arithmetic operation Yes
SIGHUP Controlling terminal hangup. No
SIGILL Execution of an illegal machine instruction. Yes
SIGINT Terminal interrupt signal, generated by Ctrl-c. No
Sure Kill (cannot be caught or ignored), generated by:
SIGKILL Yes
kill -9 PID command.
SIGPIPE Write on a pipe with no one to read it. Yes
Terminal quit signal commonly generated by a control \
SIGQUIT Yes
keys.
Segmentation fault, generated by de-referencing a NULL
SIGSEGV Yes
pointer.
SIGTERM Termination signal, can be generated by : kill pid command Yes
SIGUSR1 User-defined signal 1. No
SIGUSR2 User-defined signal 2. No
o Process table in the kernel table has a slot contaning array of signal flags
o When a signal is generated kernel will set the corresponding signal flag in
the process table entry.
o Then kernel consults the array entry of the corresponding signal to find out
how the process will react to the pending signal.
o delivered signal: If a signal has been reacted or action taken for a sign.
#include <signal.h>
The signal function establishes action as the action for the signal signum. The
first argument, signum, identifies the signal whose behavior you want to control, and
The second argument, action, specifies the action to use for the signal signum.
SIG_DFL : It specifies the default action for the particular signal. The
default actions for various kinds of signals are
stated in Standard Signals.
If you set the action for a signal to SIG_IGN, or if you set it to SIG_DFL
and the default action is to ignore that signal, then any pending
signals of that type are discarded (even if they are blocked).
Discarding the pending signals means that they will never be
delivered, not even if you subsequently specify another action
and unblock this kind of signal.
The signal function returns the action that was previously in effect for the specified
signum. You can save this value and restore it later by calling signal again.
#include <signal.h>
sighandler_t sa_handler:
This is used in the same way as the action argument to the signal function. The
value can be SIG_DFL, SIG_IGN, or a function pointer.
sigset_t sa_mask:
sa_flags:
This specifies various flags which can affect the behavior of the signal. The
sa_flags member of the sigaction structure is a catch-all for special features.
The value of sa_flags is interpreted as a bit mask. Thus, you should choose the
flags you want to set, OR those flags together, and store the result in the sa_flags
member of your sigaction structure.
Signal Sets
All of the signal blocking functions use a data structure called a signal set to
specify what signals are affected.
You must always initialize the signal set with one of these two functions before
using it in any other way.
This function clears all signal flags in the set argument and always returns 0.
This function sets all the signal in the set argument and the return value is 0.
This function adds the signal signum to the signal set set. All sigaddset does is
modify set; it does not block or unblock any signals. The return value is 0 on success and
-1 on failure.
This function removes the signal signum from the signal set set. All sigdelset
does is modify set; it does not block or unblock any signals. The return value and error
conditions are the same as for sigaddset.
The sigismember function tests whether the signal signum is a member of the
signal set set. It returns 1 if the signal is in the set, 0 if not, and -1 if there is an error.
The collection of signals that are currently blocked is called the signal mask. You
can block or unblock signals with total flexibility by modifying the signal mask.
int sigprocmask (int how, const sigset_t *restrict set, sigset_t *restrict oldset);
The last argument, oldset, is used to return information about the old process
signal mask.
You can't block the SIGKILL and SIGSTOP signals, but if the signal set includes
these, sigprocmask just ignores them instead of returning an error status.
When a child process terminates or stops, the kernel will generate a SIGCHLD
signal to its parent process. Depending on how parent sets up the handling of the
SIGCHLD signal, different events may occur.
1. Parent may accept the default action of the SIGCHLD signal:unlike other signals
SIGCHLD signal does not terminate the parent process. It affects only the parent
process if it arrives at the same time the parentprocess is suspended by the waitpid
system call. If that is the case, the parent process will be awakened, The API will
return the child’s exit status and process ID to the parent, and the kernel will clear
up the Process table slot allocated for the child process. Thus with this setup, a
parent process can call the waitpid API repeatedly to wait for each child it
created.
2. Parent ignores the SIGCHLD signal: The SIGCHLD signal will be discarded, and
the parent will not be disturbed, even if it is executing the waitpid system call.
The effect of this setup is that if the parent calls the waitpid system call. The API
will suspend the parent until all its child process have terminated and the kernel
will clear up the Process table slot allocated for the child process and the API will
return -1 to the parent process.
3. Process catches the SIGCHLD signal: the signal handler function will be called in
the parent process whenever a child process terminates. Furtheremore, if the
SIGCHLD signal arrives while the parent process is executing the waitpid system
call, after the signal handler function returns, the waitpid API may be restarted to
The interaction between SIGCHLD and wait API is the same as that
between SIGCHLD and the waitpid API
These are used to transfer control fron one function to another hence they are
called non-local goto statements. The function prototype of these functions are:
#include <setjmp.h>
The sigsetjmp behaves similarly to the setjmp APIs, except that it has a second
argument, save_sigmask, which allows a user to specify whether a calling process signal
mask should be saved to the provided env argument.
Similarly the siglongjmp does all the operations as the longjmpAPI, but it also
restores a calling process signal mask if the mask was saved in its env argument. The
retval argument specifies the return value of the corresponding sigsetjmp API when it is
called by siglongjmp. It value should be a non-zero number, if it is zero the siglongjmp
API will reset it to 1.
The siglongjmp API is usually called from user defined signal handling functions.
A process can send itself a signal with the raise function. This function is
declared in signal.h.
#include <signal.h>
#include <signal.h>
The pid specifies the process or process group to receive the signal:
The pause function suspends program execution until a signal arrives whose
action is either to execute a handler function, or to terminate the process.
#include <unistd.h>
int pause( );
alarm
The alarm API can be called by a process to request the kernel to send the
SIGALRM signal after a certain number of real clock seconds. This is just like setting
alarm clock to remind someone to do smething after a specific period of time.
#include <signal’s>
#include <unistd.h>
unsigned int sleep (unsigned int seconds);
Daemon Process
Daemon Characteristics
ps –axj
-a: Option shows the status of all the processes owned by others
-x: Shows process that does not have a controlling terminal
-j: Option displays the job related information:
Processes 0, 1, and 2 are the process IDs of swapper, init and pagedaemon
respectively and they are existing for the entire lifetime of the system. They have no
Parent process group ID, and no session ID.
update is a program that flushes the kernel's buffer cache to disk at regular
intervals (usually every 30 seconds). To-do this it just calls the sync function every 30
seconds.
Notice that, all the daemons run with super user privileges (user ID of 1). None of
the daemons has a controlling terminal: The terminal name is set to a question mark.
Coding Rules
1. The first thing to do is call fork and has the parent exit.
2. Call setsid to create a new session and performs the followings: The process
a. Becomes a session leader of a new session
b. Becomes the process group leader of a new process group
c. Has no controlling terminal.
int daemon_init(void)
{
pid_t pid;
Error Logging
One problem a daemon has is how to handle error messages. It can't just
write to standard error" since it shouldn't have a controlling terminal.
Each log message can be routed to one of three loggers: the error logger,
the trace logger, or the console logger.
There are three ways to generate log messages and three ways to read them.
1. Routines within the kernel can call strlog to generate log messages. This
is normally used by streams modules and streams device drivers for either
error messages or trace messages.
2. The normal trace logger is strace. It can selectively write a specified set
of trace messages to its standard output.
Client-Server Model
A common use for a daemon process is as a server process. Indeed, in the above
diagram we can call the syslogd process a server that has messages sent to it by user
processes (clients) using a UNIX domain datagram socket.
In general, a server is a process that waits for a client to contact it, requesting
some type of service. In the above, diagram the service being provided by the syslogd
server is the logging of an error message.
Pipes
A pipe is a mechanism for interprocess communication
Data written to the pipe by one process can be read by another process
The data is handled in a first-in, first-out (FIFO) order.
The pipe has no name
Limitations of pipe
Creating a Pipe
#include <unistd.h>
int pipe (int filedes[2]);
The following program creates, writes to, and reads from a pipe.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
int main()
{
int pfds[2];
char buf[30];
if (pipe(pfds) == -1) {
perror("pipe");
exit(1);
}
The popen function is closely related to the system function; it executes the shell
command command as a sub process.
Coprocesses
A Unix filter is a program that reads from standard input and writes to
standard output. A filters are normally connected linearly in shell
pipelines. A filter becomes a coprocess when the same program genarates
its input and reads its output.
A coprocess normally runs in the background from a shell and its standard
input and standard output are connected to another program using pipe.
Example : A process creates two pipes: one to its standard input and one
to its standard output of the coprocess, as shown in figure.
Parent Child(Coprocess)
Pipe1
fdisc[1] stdin
fdisc[2] stdout
Pipe 2
FIFOs
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
IPC methods are defined in POSIX.lb (the standard for a portable real-
time operating system).
They are messages, shared memory, and semaphores. The System V
messages, shared memory, and semaphores use integer keys as identifiers
(names).
A message queue table in a kernel address space that keeps track of all message
queues created in a system. Each entry of the message tables stores the following data for
one message queue:
The creator user ID and group ID. A process whose effective user ID
matches a message queue creator user ID may delete the queue and also
change the queue control data
The assigned owner user ID and group ID. These are normally the same as
those of the creator, but a creator can set these values to reassign the queue
owner and group membership
Read-write access permission of the queue for owner, group members, or
others. A process that has read permission to the queue may retrieve
messages from the queue, query the assigned user, and group IDs of the
queue. A process that has write permission to a queue may send messages
to the queue
The time and process ID of the last process that sent a message to the
queue
The Time and process ID of the last process that read a message from the
queue
The pointer to a linked list of message records in the queue. Each message
recordstores one message of data and its assigned message type
Message record
Message Table
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/message.h>
int msgget ( key _t key, int flag );
int msgsnd (int msgfd, const void* msgPtr, int len, int flag );
int msgrcv (int msgfd, const void* msgPtr, int len, int mtype, int flag );
int msgctl (int msgfd, int cmd, struct msqid_ds* mbufPtr );
Semaphores
In UNIX System, there is a semaphore table in the kernel, address space that
keeps track of all semaphore sets created in the system.
Each entry of the semaphore table stores the following data for one semaphore
set:
A name that is an integer ID key assigned by the process, which created
the set. Other processes may specify this key to open the set and get a
descriptor for future access of the set
The creator user ID and group ID. A process whose effective user ID
matches a semaphore set creator user ID may, delete the set and also
change control data of the set
The assigned owner user ID and group ID. These are normally the Same
as the creator user and group IDs, but a creator process can set these
values to assign a different owner and group membership for the set
Read-write access permission of the set for owner, group members, and
others. A process that has read permission to the set may query values of
the semaphores and queries the assigned users and group IDs of the set. A
process that has write permission to a set may change the values of
semaphores
The number of semaphores in the set
The time when the last process changed one or more semaphore values
The time when the last process changed the control data of the set
Semaphore set
Semaphore Table
In addition to the above, the struct sem data type, as defined in the <sys/sem.h>
header, defines the data stored in a semaphore:
In UNIX System V.3 and V.4, there is a shared memory table in the kernel
address space that keeps track of all shared memory regions created in the system. Each
entry of the table stores the following data for one shared memory region:
A name that is an integer ID key assigned by the process that created the
shared memory. Other processes may specify this key to "open" the region
and get a descriptor for future attachment to or detachment from the region
The creator user and group IDs. A process whose effective user ID
matches a shared memory region creator user ID may delete the region
and may change control data of the region
The assigned owner user and group IDs. These are normally the same as
those of that creator user and group IDs, but a creator process can set these
values to assign different owner and group membership for the region
Read-write access permission of the region for owner, group members,
and others. A process that has read permission to the region may read data
from it and query the assigned user and group IDs of the region. A process
that has write permission to a region may write data to it
The size, in number of bytes, of the shared memory region
The time when the last process attached to the region
The time when the last process detached from the region
The time when the last process changed control data of the region
#include <sys/types.h>
Stream Pipes
s_pipe
This function just calls the standard pipe function, which creates a full-duplex pipe.
I
#include <stdio.h>
int s_pipe(int fd[2]) /* two file descriptors returned in int fd[O] & fd[l] */
{
return ( pipe(fd) );
}
Figure shows pipe looks like under SVR4, Just two stream heads are connected to
each other.
fd flags ptr
fd 0
…….
fd 1
fd2
File table
File status
Process table entry flagsCurrent file
offsetv-node ptr
V- node table
v-node
fd 0
fd flags ptr Informationi-
fd 1
node
fd2
………… Information
fd3
Current file size
Figure: Passing an open file from the top process to the bottom process
The following three user-defined functions are used to send and receive file
descriptors.
#include <stdio.h>
#include <unistd.h>
o send_fd sends the descriptor filedes across the stream pipe spipefd.
o send_err sends the errmsg across the stream pipe spipefd.
o recv_fd is called by the client to receive a descriptor.
Stream pipes are useful for IPC between related processes, such as a parent and
child.
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>