152
Unix and network Programming MC0618 2012 SRM University Department of Computer Applications S.Kanchana Devi Syllobus File I/O – study of open, close, read, write, lseek, dup system calls Files & directories - study of stat, access, chmod, link, unlink and directory related system calls - time and date routines – setjmp and longjmp functions Process Control – fork, vfork, exec, and wait functions. Signals - Concepts – various signals - signal handling – blocking, suspending, delivering signals – various signal related functions. IPC – Pipes - FIFO’s - Message queue – Semaphore – Shared memory. Sockets - Introduction - TCP Sockets – Socket Options - UDP Sockets – Echo client/server example - Name and Address Conversions. Daemon Processes and inetd SuperServer - Broadcasting – Multicasting - Out-of-Band Data – Raw Sockets - Data Link Access. TOTAL 45 TEXT BOOKS: 1. Richard Stevens.W - Advanced Programming in the Unix Environment – Pearson Education Asia -1998. 2. Richard Stevens.W- Unix Network Programming Vol - I” – Prentice hall of India - 1998. http://pubs.opengroup.org/onlinepubs/009695399/mindex.html REFERENCE BOOKS: 1. Richard Stevens.W- Unix Network Programming Vol - II – Prentice hall of Inida - 1999. 2. Stephen A.Rago –Unix System V Network Programming – Addision Wesley – 19993. Class Notes Practical Programs Model question papers

Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Embed Size (px)

Citation preview

Page 1: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Syllobus File I/O – study of open, close, read, write, lseek, dup system calls Files & directories - study of stat, access, chmod, link, unlink and directory related system calls - time and date routines – setjmp and longjmp functions Process Control – fork, vfork, exec, and wait functions. Signals - Concepts – various signals - signal handling – blocking, suspending, delivering signals – various signal related functions. IPC – Pipes - FIFO’s - Message queue – Semaphore – Shared memory. Sockets - Introduction - TCP Sockets – Socket Options - UDP Sockets – Echo client/server example - Name and Address Conversions. Daemon Processes and inetd SuperServer - Broadcasting – Multicasting - Out-of-Band Data – Raw Sockets - Data Link Access.

TOTAL 45 TEXT BOOKS:

1. Richard Stevens.W - Advanced Programming in the Unix Environment – Pearson Education Asia -1998.

2. Richard Stevens.W- Unix Network Programming Vol - I” – Prentice hall of India -

1998. http://pubs.opengroup.org/onlinepubs/009695399/mindex.html REFERENCE BOOKS:

1. Richard Stevens.W- Unix Network Programming Vol - II – Prentice hall of Inida - 1999.

2. Stephen A.Rago –Unix System V Network Programming – Addision Wesley – 19993.

Class Notes Practical Programs Model question papers

Page 2: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Page 3: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Class Notes

UNIT I File Information File is Collection of Text and alphanumeric charactes ordered as records. The file have some operations related to that. They are file open, file close, file read and file write ,lseek, dup, dup2. Various functions supporting to do file operations are following. Create Function

NAME create - create a new file or rewrite an existing one

SYNOPSIS #include<sys/stat.h> #include<fcntl.h> Int create(const char *path, mode_t mode)

DESCRIPTION

The function call: creat(path, mode)shall be equivalent to: open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)

RETURN VALUE

Refer to open().

ERRORS

Refer to open().

EXAMPLES

Creating a File

The following example creates the file /tmp/file with read and write permissions for the file owner and read permission for group and others. The resulting file descriptor is assigned to the fd variable.

#include <fcntl.h> ... int fd; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; char *filename = "/tmp/file"; ... fd = creat(filename, mode);

Page 4: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

...

NAME open - open a file

SYNOPSIS #inlude<sys/stat.h> #include <fcntl.h> int open(const char *path, intoflag, ... );

DESCRIPTION

The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file.

The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.

The file offset used to mark the current position within the file shall be set to the beginning of the file.

The file status flags and file access modes of the open file description shall be set according to the value of oflag.

Values for oflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>. Applications shall specify exactly one of the first three values (file access modes) below in the value of oflag:

O_RDONLY Open for reading only.

O_WRONLY Open for writing only.

O_RDWR Open for reading and writing. The result is undefined if this flag is applied to a FIFO.

Any combination of the following may be used:

Page 5: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

O_APPEND If set, the file offset shall be set to the end of the file prior to each write.

O_CREAT If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see <sys/stat.h>) of the file mode shall be set to the value of the third argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.

O_DSYNC [SIO] Write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.

O_EXCL If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.

O_NOCTTY If set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.

O_NONBLOCK When opening a FIFO with O_RDONLY or O_WRONLY set:

• If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading.

• If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading.

When opening a block special or character special file that supports non-blocking opens:

• If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific.

Page 6: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

• If O_NONBLOCK is clear, the open() function shall block the calling thread until the device is ready or available before returning.

Otherwise, the behavior of O_NONBLOCK is unspecified.

O_RSYNC [SIO] Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.

O_SYNC [SIO] Write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.

O_TRUNC If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of using O_TRUNC with O_RDONLY is undefined.

If O_CREAT is set and the file did not previously exist, upon successful completion, open() shall mark for update the st_atime,st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.

If O_TRUNC is set and the file did previously exist, upon successful completion, open() shall mark for update the st_ctime and st_mtime fields of the file.

• If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set.

• If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag values are not applicable to STREAMS devices and shall have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific.

• If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Conforming applications shall call unlockpt() before opening the slave side.

The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description.

Page 7: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

RETURN VALUE

Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.

Example Program

Opening a File for Writing

The following example opens a file for writing, creating the file if it does not already exist. If the file does exist, the system truncates the file to zero bytes.

#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #define LOCKFILE "/etc/ptmp" ... int pfd; char filename[PATH_MAX+1]; ... if ((pfd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1) { perror("Cannot open output file\n"); exit(1); }

...

Opening a File Using an Existence Check

The following example uses the open() function to try to create the LOCKFILE file and open it for writing. Since the open() function specifies the O_EXCL flag, the call fails if the file already exists. In that case, the program assumes that someone else is updating the password file and exits.

#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #define LOCKFILE "/etc/ptmp"

Page 8: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

... int pfd; /* Integer for file descriptor returned by open() call. */ ... if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1) { fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n"); exit(1); }

NAME

read - read from a file

SYNOPSIS

#include <unistd.h> ssize_t read(intfildes, void *buf, size_tnbyte);

DESCRIPTION

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

Before any action described below is taken, and if nbyte is zero, the read() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall return zero and have no other results.

On files that support seeking (for example, a regular file), the read() shall start at a position in the file given by the file offset associated with fildes. The file offset shall be incremented by the number of bytes actually read.

Files that do not support seeking-for example, terminals-always read from the current position. The value of a file offset associated with such a file is undefined.

No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-defined.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined.

When attempting to read from an empty pipe or FIFO:

• If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file. • If some process has the pipe open for writing and O_NONBLOCK is set, read() shall

return -1 and set errno to [EAGAIN].

Page 9: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

• If some process has the pipe open for writing and O_NONBLOCK is clear, read() shall block the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing.

When attempting to read a file (other than a pipe or FIFO) that supports non-blocking reads and has no data currently available:

• If O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN]. • If O_NONBLOCK is clear, read() shall block the calling thread until some data becomes

available. • The use of the O_NONBLOCK flag has no effect if there is some data available.

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads in the gap between the previous end of data and the newly written data shall return bytes with value 0 until data is written into the gap.

Upon successful completion, where nbyte is greater than 0, read() shall mark for update the st_atime field of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.

• If a read() is interrupted by a signal before it reads any data, it shall return -1 with errno set to [EINTR].

• If a read() is interrupted by a signal after it has successfully read some data, it shall return the number of bytes read.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with fildes.

If fildes refers to a socket, read() shall be equivalent to recv() with no flags set.

• If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.

• If fildes refers to a shared memory object, the result of the read() function is unspecified. • If fildes refers to a typed memory object, the result of the read() function is unspecified. • A read() from a STREAMS file can read data in three different modes: byte-stream

mode, message-nondiscard mode, and message-discard mode. The default shall be byte-stream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested with I_GRDOPT ioctl(). In byte-stream mode, read() shall retrieve data from the

Page 10: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

STREAM until as many bytes as were requested are transferred, or until there is no more data to be retrieved. Byte-stream mode ignores message boundaries.

In STREAMS message-nondiscard mode, read() shall retrieve data until as many bytes as were requested are transferred, or until a message boundary is reached. If read() does not retrieve all the data in a message, the remaining data shall be left on the STREAM, and can be retrieved by the next read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a message after the read() returns shall be discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call.

How read() handles zero-byte STREAMS messages is determined by the current read mode setting. In byte-stream mode, read() shall accept data until it has read nbyte bytes, or until there is no more data to read, or until a zero-byte message block is encountered. The read() function shall then return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In message-nondiscard mode or message-discard mode, a zero-byte message shall return 0 and the message shall be removed from the STREAM. When a zero-byte message is read as the first message on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read mode.

A read() from a STREAMS file shall return the data in the message at the front of the STREAM head read queue, regardless of the priority band of the message.

By default, STREAMs are in control-normal mode, in which a read() from a STREAMS file can only process messages that contain a data part but do not contain a control part. The read() shall fail if a message containing a control part is encountered at the STREAM head. This default action can be changed by placing the STREAM in either control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In control-data mode, read() shall convert any control part to data and pass it to the application before passing any data part originally present in the same message. In control-discard mode, read() shall discard message control parts but return to the process any data part in the message.

In addition, read() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno shall not reflect the result of read(), but reflect the prior error. If a hangup occurs on the STREAM being read, read() shall continue to operate normally until the STREAM head read queue is empty. Thereafter, it shall return 0.

• The pread() function shall be equivalent to read(), except that it shall read from a given position in the file without changing the file pointer. The first three arguments to pread() are the same as read() with the addition of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall result in an error.

Page 11: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

RETURN VALUE

Upon successful completion, read() and pread()shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return -1 and set errno to indicate the error.

EXAMPLES

Reading Data into a Buffer

The following example reads data from the file associated with the file descriptor fd into the buffer pointed to by buf.

#include <sys/types.h> #include <unistd.h> ... char buf[20]; size_t nbytes; ssize_t bytes_read; int fd; ... nbytes = sizeof(buf); bytes_read = read(fd, buf, nbytes); ...

NAME

write - write on a file

SYNOPSIS

#include <unistd.h>

ssize_t write(intfildes, const void *buf, size_tnbyte);

DESCRIPTION

The write() function shall attempt to write nbyte bytes from the buffer pointed to by buf to the file associated with the open file descriptor, fildes.

Before any action described below is taken, and if nbyte is zero and the file is a regular file, the write() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the write() function shall return zero and have no other results. If nbyte is zero and the file is not a regular file, the results are unspecified.

Page 12: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset shall be incremented by the number of bytes actually written. On a regular file, if this incremented file offset is greater than the length of the file, the length of the file shall be set to this file offset.

On a file not capable of seeking, writing shall always take place starting at the current position. The value of a file offset associated with such a device is undefined.

If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.

If a write() requests that more bytes be written than there is room for (for example, the process' file size limit or the physical end of a medium), only as many bytes as there is room for shall be written. For example, suppose there is space for 20 bytes more in a file before reaching a limit. A write of 512 bytes will return 20. The next write of a non-zero number of bytes would give a failure return (except as noted below).

If the request would cause the file size to exceed the soft file size limit for the process and there is no room for any bytes to be written, the request shall fail and the implementation shall generate the SIGXFSZ signal for the thread.

• If write() is interrupted by a signal before it writes any data, it shall return -1 with errno set to [EINTR].

• If write() is interrupted by a signal after it successfully writes some data, it shall return the number of bytes written.

• If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined.

After a write() to a regular file has successfully returned:

• Any successful read() from each byte position in the file that was modified by that write shall return the data specified by the write() for that position until such byte positions are again modified.

• Any subsequent successful write() to the same byte position in the file shall overwrite that file data.

Upon successful completion, where nbyte is greater than 0, write() shall mark for update the st_ctime and st_mtime fields of the file, and if the file is a regular file, the S_ISUID and S_ISGID bits of the file mode may be cleared.

Lseek function

NAME lseek - move the read/write file offset

Page 13: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

SYNOPSIS #include <unistd.h> off_t lseek(intfildes, off_toffset, intwhence);

DESCRIPTION

The lseek() function shall set the file offset for the open file description associated with the file descriptor fildes, as follows:

• If whence is SEEK_SET, the file offset shall be set to offset bytes. • If whence is SEEK_CUR, the file offset shall be set to its current location plus offset. • If whence is SEEK_END, the file offset shall be set to the size of the file plus offset.

The symbolic constants SEEK_SET, SEEK_CUR, and SEEK_END are defined in <unistd.h>.

The behavior of lseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.

The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

The lseek() function shall not, by itself, extend the size of a file.

• If fildes refers to a shared memory object, the result of the lseek() function is unspecified.

• If fildes refers to a typed memory object, the result of the lseek() function is unspecified.

RETURN VALUE

Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned. Otherwise, (off_t)-1 shall be returned, errno shall be set to indicate the error, and the file offset shall remain unchanged

Dup dup2 functions

NAME dup, dup2 - duplicate an open file descriptor

Page 14: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

SYNOPSIS

#include <unistd.h> int dup(intfildes); int dup2(intfildes, intfildes2);

DESCRIPTION

The dup() function provides an alternative interface to the service provided by fcntl() using the F_DUPFD command. The call dup(fildes) shall be equivalent to:

fcntl(fildes, F_DUPFD, 0);

The dup2() function shall cause the file descriptor fildes2 to refer to the same open file description as the file descriptor fildes and to share any locks, and shall return fildes2. If fildes2 is already a valid open file descriptor, it shall be closed first, unless fildes is equal to fildes2 in which case dup2() shall return fildes2 without closing it. If the close operation fails to close fildes2, dup2() shall return -1 without changing the open file description to which fildes2 refers. If fildes is not a valid file descriptor, dup2() shall return -1 and shall not close fildes2. If fildes2 is less than 0 or greater than or equal to {OPEN_MAX}, dup2() shall return -1 with errno set to [EBADF].

Upon successful completion, if fildes is not equal to fildes2, the FD_CLOEXEC flag associated with fildes2 shall be cleared. If fildes is equal to fildes2, the FD_CLOEXEC flag associated with fildes2 shall not be changed.

• If fildes refers to a typed memory object, the result of the dup2() function is unspecified.

RETURN VALUE

Upon successful completion a non-negative integer, namely the file descriptor, shall be returned; otherwise, -1 shall be returned and errno set to indicate the error

EXAMPLES

Redirecting Standard Output to a File

The following example closes standard output for the current processes, re-assigns standard output to go to the file referenced by pfd, and closes the original file descriptor to clean up.

#include <unistd.h> ... int pfd; ... close(1);

Page 15: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

dup(pfd); close(pfd); ...

Redirecting Error Messages

The following example redirects messages from stderr to stdout.

#include <unistd.h> ... dup2(1, 2);

UNIT II

Directory related Functions Directory Structure and Files

The following directories shall exist on conforming systems and conforming applications shall make use of them only as described. Strictly conforming applications shall not assume the ability to create files in any of these directories, unless specified below.

/ The root directory.

/dev Contains /dev/console, /dev/null, and /dev/tty, described below.

The following directory shall exist on conforming systems and shall be used as described:

/tmp A directory made available for applications that need a place to create temporary files. Applications shall be allowed to create files in this directory, but shall not assume that such files are preserved between invocations of the application.

The following files shall exist on conforming systems and shall be both readable and writable:

/dev/null

Page 16: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

An infinite data source and data sink. Data written to /dev/null shall be discarded. Reads from /dev/null shall always return end-of-file (EOF).

/dev/tty In each process, a synonym for the controlling terminal associated with the process group of that process, if any. It is useful for programs or shell procedures that wish to be sure of writing messages to or reading data from the terminal no matter how output has been redirected. It can also be used for applications that demand the name of a file for output, when typed output is desired and it is tiresome to find out what terminal is currently in use.

The following file shall exist on conforming systems and need not be readable or writable:

/dev/console The /dev/console file is a generic name given to the system console (see System Console). It is usually linked to an implementation-defined special file. It shall provide an interface to the system console conforming to the requirements of the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

Stat function

NAME stat - get file status

SYNOPSIS #include <sys/stat.h> int stat(const char *restrictpath, struct stat *restrictbuf);

DESCRIPTION

The stat() function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file. Read, write, or execute permission of the named file is not required. An implementation that provides additional or alternate file access control mechanisms may, under implementation-defined conditions, cause stat() to fail. In particular, the system may deny the existence of the file specified by path.

If the named file is a symbolic link, the stat() function shall continue pathname resolution using the contents of the symbolic link, and shall return information pertaining to the resulting file if the file exists.

The buf argument is a pointer to a stat structure, as defined in the <sys/stat.h> header, into which information is placed concerning the file.

The stat() function shall update any time-related fields (as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.7, File Times Update), before writing into the stat structure.

Page 17: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Unless otherwise specified, the structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime shall have meaningful values for all file types defined in this volume of IEEE Std 1003.1-2001. The value of the member st_nlink shall be set to the number of links to the file.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The stat() function shall fail if:

[EACCES] Search permission is denied for a component of the path prefix.

[EIO] An error occurred while reading from the file system.

[ELOOP] A loop exists in symbolic links encountered during resolution of the path argument.

[ENAMETOOLONG] The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

[ENOENT] A component of path does not name an existing file or path is an empty string.

[ENOTDIR] A component of the path prefix is not a directory.

[EOVERFLOW] The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The stat() function may fail if:

[ELOOP] More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.

[ENAMETOOLONG] As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

[EOVERFLOW] A value to be stored would overflow one of the members of the stat structure.

Page 18: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

EXAMPLES

Obtaining File Status Information

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure.

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> struct stat buffer; int status; ... status = stat("/home/cnd/mod1", &buffer);

Getting Directory Information

The following example fragment gets status information for each entry in a directory. The call to the stat() function stores file information in the stat structure pointed to by statbuf. The lines that follow the stat() call format the fields in the stat structure for presentation to the user of the program.

#include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <pwd.h> #include <grp.h> #include <time.h> #include <locale.h> #include <langinfo.h> #include <stdio.h> #include <stdint.h> struct dirent *dp; struct stat statbuf; struct passwd *pwd; struct group *grp; struct tm *tm; char datestring[256]; ... /* Loop through directory entries. */

Page 19: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

while ((dp = readdir(dir)) != NULL) {

/* Print out type, permissions, and number of links. */ printf("%10.10s", sperm (statbuf.st_mode)); printf("%4d", statbuf.st_nlink);

/* Print out group name if it is found using getgrgid(). */ if ((grp = getgrgid(statbuf.st_gid)) != NULL) printf(" %-8.8s", grp->gr_name); else printf(" %-8d", statbuf.st_gid); /* Print size of file. */ printf(" %9jd", (intmax_t)statbuf.st_size);

tm = localtime(&statbuf.st_mtime); /* Get localized date string. */ strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm); printf(" %s %s\n", datestring, dp->d_name);

}

NAME fstat - get file status

SYNOPSIS

#include <sys/stat.h> int fstat(intfildes, struct stat *buf);

DESCRIPTION

The fstat() function shall obtain information about an open file associated with the file descriptor fildes, and shall write it to the area pointed to by buf.

Page 20: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

• If fildes references a shared memory object, the implementation shall update in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_mode fields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits need be valid. The implementation may update other fields and flags.

• If fildes references a typed memory object, the implementation shall update in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_mode fields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits need be valid. The implementation may update other fields and flags.

The buf argument is a pointer to a stat structure, as defined in <sys/stat.h>, into which information is placed concerning the file.

The structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime shall have meaningful values for all other file types defined in this volume of IEEE Std 1003.1-2001. The value of the member st_nlink shall be set to the number of links to the file.

ERRORS

The fstat() function shall fail if:

[EBADF] The fildes argument is not a valid file descriptor.

[EIO] An I/O error occurred while reading from the file system.

[EOVERFLOW] The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The fstat() function may fail if:

[EOVERFLOW] One of the values is too large to store into the structure pointed to by the buf argument.

EXAMPLES

Obtaining File Status Information

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure. The /home/cnd/mod1 file is opened with read/write privileges and is passed to the open file descriptor fildes.

#include <sys/types.h> #include <sys/stat.h>

Page 21: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

#include <fcntl.h> struct stat buffer; int status; ... fildes = open("/home/cnd/mod1", O_RDWR); status = fstat(fildes, &buffer);

NAME

lstat - get symbolic link status

SYNOPSIS

#include <sys/stat.h> int lstat(const char *restrict path, struct stat *restrict buf);

DESCRIPTION

The lstat() function shall be equivalent to stat(), except when path refers to a symbolic link. In that case lstat() shall return information about the link, while stat() shall return information about the file the link references.

For symbolic links, the st_mode member shall contain meaningful information when used with the file type macros, and the st_size member shall contain the length of the pathname contained in the symbolic link. File mode bits and the contents of the remaining members of the stat structure are unspecified. The value returned in the st_size member is the length of the contents of the symbolic link, and does not count any trailing null.

ERRORS

The lstat() function shall fail if:

[EACCES] A component of the path prefix denies search permission.

[EIO] An error occurred while reading from the file system.

[ELOOP] A loop exists in symbolic links encountered during resolution of the path argument.

[ENAMETOOLONG] The length of a pathname exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

[ELOOP]

Page 22: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.

[ENAMETOOLONG] As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

[EOVERFLOW] One of the members is too large to store into the structure pointed to by the buf argument.

EXAMPLES

Obtaining Symbolic Link Status Information

The following example shows how to obtain status information for a symbolic link named /modules/pass1. The structure variable buffer is defined for the stat structure. If the path argument specified the filename for the file pointed to by the symbolic link ( /home/cnd/mod1), the results of calling the function would be the same as those returned by a call to the stat() function.

#include <sys/stat.h> struct stat buffer; int status; ... status = lstat("/modules/pass1", &buffer);

NAME

fstat - get file status

SYNOPSIS

#include <sys/stat.h> int fstat(int fildes, struct stat *buf);

DESCRIPTION

The fstat() function shall obtain information about an open file associated with the file descriptor fildes, and shall write it to the area pointed to by buf.

• If fildes references a shared memory object, the implementation shall update in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_modefields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and

Page 23: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

S_IWOTH file permission bits need be valid. The implementation may update other fields and flags.

• If fildes references a typed memory object, the implementation shall update in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_mode fields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits need be valid. The implementation may update other fields and flags.

The buf argument is a pointer to a stat structure, as defined in <sys/stat.h>, into which information is placed concerning the file.

The structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime shall have meaningful values for all other file types defined in this volume of IEEE Std 1003.1-2001. The value of the member st_nlink shall be set to the number of links to the file.

An implementation that provides additional or alternative file access control mechanisms may, under implementation-defined conditions, cause fstat() to fail.

The fstat() function shall update any time-related fields as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.7, File Times Update, before writing into the stat structure.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The fstat() function shall fail if:

[EBADF] The fildes argument is not a valid file descriptor.

[EIO] An I/O error occurred while reading from the file system.

[EOVERFLOW] The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The fstat() function may fail if:

[EOVERFLOW] One of the values is too large to store into the structure pointed to by the buf argument.

EXAMPLES

Page 24: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Obtaining File Status Information

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure. The /home/cnd/mod1 file is opened with read/write privileges and is passed to the open file descriptor fildes.

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> struct stat buffer; int status; ... fildes = open("/home/cnd/mod1", O_RDWR); status = fstat(fildes, &buffer);

NAME

time.h - time types

SYNOPSIS

#include <time.h>

DESCRIPTION

The <time.h> header shall declare the structure tm, which shall include at least the following members:

int tm_sec Seconds [0,60]. int tm_min Minutes [0,59]. int tm_hour Hour [0,23]. int tm_mday Day of month [1,31]. int tm_mon Month of year [0,11]. int tm_year Years since 1900. int tm_wday Day of week [0,6] (Sunday =0). int tm_yday Day of year [0,365]. int tm_isdst Daylight Savings flag.

The value of tm_isdst shall be positive if Daylight Savings Time is in effect, 0 if Daylight Savings Time is not in effect, and negative if the information is not available.

Page 25: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The <time.h> header shall define the following symbolic names:

NULL Null pointer constant.

CLOCKS_PER_SEC A number used to convert the value returned by the clock() function into seconds.

CLOCK_PROCESS_CPUTIME_ID [TMR|CPT] The identifier of the CPU-time clock associated with the process making a clock() or timer*() function call.

CLOCK_THREAD_CPUTIME_ID [TMR|TCT] The identifier of the CPU-time clock associated with the thread making a clock() or timer*() function call.

[TMR] The <time.h> header shall declare the structure timespec, which has at least the following members:

time_t tv_sec Seconds. long tv_nsec Nanoseconds.

The <time.h> header shall also declare the itimerspec structure, which has at least the following members:

struct timespec it_interval Timer period. struct timespec it_value Timer expiration.

The following manifest constants shall be defined:

CLOCK_REALTIME The identifier of the system-wide realtime clock.

TIMER_ABSTIME Flag indicating time is absolute. For functions taking timer objects, this refers to the clock associated with the timer.

CLOCK_MONOTONIC [MON] The identifier for the system-wide monotonic clock, which is defined as a clock whose value cannot be set via clock_settime() and which cannot have backward clock jumps. The maximum possible clock jump shall be implementation-defined.

The clock_t, size_t, time_t, [TMR] clockid_t, and timer_t types shall be defined as described in <sys/types.h> .

Page 26: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

[XSI] Although the value of CLOCKS_PER_SEC is required to be 1 million on all XSI-conformant systems, it may be variable on other systems, and it should not be assumed that CLOCKS_PER_SEC is a compile-time constant.

[XSI] The <time.h> header shall provide a declaration for getdate_err.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

• char *asctime(const struct tm *); • char *asctime_r(const struct tm *restrict, char *restrict); • clock_t clock(void) • int clock_gettime(clockid_t, struct timespec *); • int clock_settime(clockid_t, const struct timespec *); • char *ctime(const time_t *);[TSF] • char *ctime_r(const time_t *, char *); • double difftime(time_t, time_t);

• struct tm *getdate(const char *); • struct tm *gmtime(const time_t *); • struct tm *gmtime_r(const time_t *restrict, struct tm *restrict); • struct tm *localtime(const time_t *); • struct tm *localtime_r(const time_t *restrict, struct tm *restrict); • time_t mktime(struct tm *); • int nanosleep(const struct timespec *, struct timespec *); • size_t strftime(char *restrict, size_t, const char *restrict, • const struct tm *restrict); • char *strptime(const char *restrict, const char *restrict, • struct tm *restrict); • time_t time(time_t *); • int timer_create(clockid_t, struct sigevent *restrict, • timer_t *restrict); • int timer_delete(timer_t); • int timer_gettime(timer_t, struct itimerspec *); • int timer_getoverrun(timer_t); • int timer_settime(timer_t, int, const struct itimerspec *restrict, • struct itimerspec *restrict); • void tzset(void);

NAME

Page 27: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

asctime, asctime_r - convert date and time to a string

SYNOPSIS

#include <time.h> char *asctime(const struct tm *timeptr);

DESCRIPTION

For asctime(): [CX] The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The asctime() function shall convert the broken-down time in the structure pointed to by timeptr into a string in the form:

Sun Sep 16 01:03:52 1973\n\0

using the equivalent of the following algorithm:

char *asctime(const struct tm *timeptr) { static char wday_name[7][3] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char mon_name[12][3] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char result[26]; sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n", wday_name[timeptr->tm_wday], mon_name[timeptr->tm_mon], timeptr->tm_mday, timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec, 1900 + timeptr->tm_year); return result; }

The tm structure is defined in the <time.h> header.

Page 28: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

• The asctime(), ctime(), gmtime(), and localtie() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

• The asctime () function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

• The asctime_r () function shall convert the broken-down time in the structure pointed to by tm into a string (of the same form as that returned by asctime ()) that is placed in the user-supplied buffer pointed to by buf (which shall contain at least 26 bytes) and then return buf.

RETURN VALUE

Upon successful completion, asctime() shall return a pointer to the string. If the function is unsuccessful, it shall return NULL.

Upon successful completion, asctime_r() shall return a pointer to a character string containing the date and time. This string is pointed to by the argument buf. If the function is unsuccessful, it shall return NULL.

NAME

ctime, ctime_r - convert a time value to a date and time string

SYNOPSIS

#include <time.h> char *ctime(const time_t *clock);

DESCRIPTION

For ctime():

The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The ctime() function shall convert the time pointed to by clock, representing time in seconds since the Epoch, to local time in the form of a string. It shall be equivalent to:asctime(localtime(clock))

The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

Page 29: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The ctime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The ctime_r() function shall convert the calendar time pointed to by clock to local time in exactly the same form as ctime() and put the string into the array pointed to by buf (which shall be at least 26 bytes in size) and return buf.

Unlike ctime(), the thread-safe version ctime_r() is not required to set tzname.

RETURN VALUE

The ctime() function shall return the pointer returned by asctime() with that broken-down time as an argument.

Upon successful completion, ctime_r() shall return a pointer to the string pointed to by buf. When an error is encountered, a null pointer shall be returned

NAME

gmtime, gmtime_r - convert a time value to a broken-down UTC time

SYNOPSIS

#include <time.h> struct tm *gmtime(const time_t *timer);

DESCRIPTION

For gmtime():

The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

NAME

localtime, localtime_r - convert a time value to a broken-down local time

SYNOPSIS

Page 30: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

#include <time.h> struct tm *localtime(const time_t *timer);

DESCRIPTION

For localtime():

The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The localtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as a local time. The function corrects for the timezone and any seasonal time adjustments. Local timezone information is used as though localtime() calls tzset().

The relationship between a time in seconds since the Epoch used as an argument to localtime() and the tm structure (defined in the <time.h> header) is that the result shall be as specified in the expression given in the definition of seconds since the Epoch (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.14, Seconds Since the Epoch) corrected for timezone and any seasonal time adjustments, where the names in the structure and in the expression correspond.

NAME

clock - report CPU time used

SYNOPSIS

#include <time.h> clock_t clock(void);

DESCRIPTION

The clock() function shall return the implementation's best approximation to the processor time used by the process since the beginning of an implementation-defined era related only to the process invocation.

RETURN VALUE

To determine the time in seconds, the value returned by clock() should be divided by the value of the macro CLOCKS_PER_SEC. [XSI] CLOCKS_PER_SEC is defined to be one million in <time.h>. If the processor time used is not available or its value cannot be represented, the function shall return the value ( clock_t)-1.

Page 31: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

NAME mktime - convert broken-down time into time since the Epoch

SYNOPSIS

#include <time.h> time_t mktime(struct tm *timeptr);

DESCRIPTION

The mktime() function shall convert the broken-down time, expressed as local time, in the structure pointed to by timeptr, into a time since the Epoch value with the same encoding as that of the values returned by time(). The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges described in <time.h>.

NAME strftime - convert date and time to a string

SYNOPSIS

#include <time.h> size_t strftime(char *restricts, size_tmaxsize, const char *restrictformat, const struct tm *restricttimeptr);

DESCRIPTION

The strftime() function shall place bytes into the array pointed to by s as controlled by the string pointed to by format. The format is a character string, beginning and ending in its initial shift state, if any. The format string consists of zero or more conversion specifications and ordinary characters. A conversion specification consists of a '%' character, possibly followed by an E or O modifier, and a terminating conversion specifier character that determines the conversion specification's behavior. All ordinary characters (including the terminating null byte) are copied unchanged into the array. If copying takes place between objects that overlap, the behavior is undefined. No more than maxsize bytes are placed into the array. Each conversion specifier is replaced by appropriate characters as described in the following list. The appropriate characters are determined using the LC_TIME category of the current locale and by the values of zero or more members of the broken-down time structure pointed to by timeptr, as specified in brackets in the description. If any of the specified values are outside the normal range, the characters stored are unspecified.

Page 32: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Local timezone information is used as though strftime() called tzset().

The following conversion specifications are supported:

%a Replaced by the locale's abbreviated weekday name. [ tm_wday]

%A Replaced by the locale's full weekday name. [ tm_wday]

%b Replaced by the locale's abbreviated month name. [ tm_mon]

%B Replaced by the locale's full month name. [ tm_mon]

%c Replaced by the locale's appropriate date and time representation. (See the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>.)

%C Replaced by the year divided by 100 and truncated to an integer, as a decimal number [00,99]. [ tm_year]

%d Replaced by the day of the month as a decimal number [01,31]. [ tm_mday]

%D Equivalent to %m / %d / %y. [ tm_mon, tm_mday, tm_year]

%e Replaced by the day of the month as a decimal number [1,31]; a single digit is preceded by a space. [ tm_mday]

%F Equivalent to %Y - %m - %d (the ISO 8601:2000 standard date format). [ tm_year, tm_mon, tm_mday]

%g Replaced by the last 2 digits of the week-based year (see below) as a decimal number [00,99]. [ tm_year, tm_wday, tm_yday]

%G Replaced by the week-based year (see below) as a decimal number (for example, 1977). [ tm_year, tm_wday, tm_yday]

%h Equivalent to %b. [ tm_mon]

%H Replaced by the hour (24-hour clock) as a decimal number [00,23]. [ tm_hour]

%I Replaced by the hour (12-hour clock) as a decimal number [01,12]. [ tm_hour]

%j Replaced by the day of the year as a decimal number [001,366]. [ tm_yday]

%m Replaced by the month as a decimal number [01,12]. [ tm_mon]

%M Replaced by the minute as a decimal number [00,59]. [ tm_min]

Page 33: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

%n Replaced by a <newline>.

%p Replaced by the locale's equivalent of either a.m. or p.m. [ tm_hour]

%r Replaced by the time in a.m. and p.m. notation; [CX] in the POSIX locale this shall be equivalent to %I : %M : %S%p. [ tm_hour, tm_min, tm_sec]

%R Replaced by the time in 24-hour notation ( %H : %M ). [ tm_hour, tm_min]

%S Replaced by the second as a decimal number [00,60]. [ tm_sec]

%t Replaced by a <tab>.

%T Replaced by the time ( %H : %M : %S ). [ tm_hour, tm_min, tm_sec]

%u Replaced by the weekday as a decimal number [1,7], with 1 representing Monday. [ tm_wday]

%U Replaced by the week number of the year as a decimal number [00,53]. The first Sunday of January is the first day of week 1; days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]

%V Replaced by the week number of the year (Monday as the first day of the week) as a decimal number [01,53]. If the week containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday]

%w Replaced by the weekday as a decimal number [0,6], with 0 representing Sunday. [ tm_wday]

%W Replaced by the week number of the year as a decimal number [00,53]. The first Monday of January is the first day of week 1; days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]

%x Replaced by the locale's appropriate date representation. (See the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>.)

%X Replaced by the locale's appropriate time representation. (See the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>.)

%y Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year]

%Y Replaced by the year as a decimal number (for example, 1997). [ tm_year]

%z

Page 34: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ), or by no characters if no timezone is determinable. For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich). [CX] If tm_isdst is zero, the standard time offset is used. If tm_isdst is greater than zero, the daylight savings time offset is used. If tm_isdst is negative, no characters are returned. [ tm_isdst]

%Z Replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists. [ tm_isdst]

%% Replaced by %.

NAME utime - set file access and modification times

SYNOPSIS

#include <utime.h> int utime(const char *path, const struct utimbuf *times);

DESCRIPTION

The utime() function shall set the access and modification times of the file named by the path argument.

If times is a null pointer, the access and modification times of the file shall be set to the current time. The effective user ID of the process shall match the owner of the file, or the process has write permission to the file or has appropriate privileges, to use utime() in this manner.

If times is not a null pointer, times shall be interpreted as a pointer to a utimbuf structure and the access and modification times shall be set to the values contained in the designated structure. Only a process with the effective user ID equal to the user ID of the file or a process with appropriate privileges may use utime() this way.

The utimbuf structure is defined in the <utime.h> header. The times in the structure utimbuf are measured in seconds since the Epoch.

Upon successful completion, utime() shall mark the time of the last file status change, st_ctime, to be updated; see <sys/stat.h>.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno shall be set to indicate the error, and the file times shall not be affected.

Page 35: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Access Function

NAME access - determine accessibility of a file

SYNOPSIS #include <unistd.h> int access(const char *path, intamode);

DESCRIPTION

The access() function shall check the file named by the pathname pointed to by the path argument for accessibility according to the bit pattern contained in amode, using the real user ID in place of the effective user ID and the real group ID in place of the effective group ID.

The value of amode is either the bitwise-inclusive OR of the access permissions to be checked (R_OK, W_OK, X_OK) or the existence tests (F_OK).

If any access permissions are checked, each shall be checked individually, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 3, Definitions. If the process has appropriate privileges, an implementation may indicate success for X_OK even if none of the execute file permission bits are set.

RETURN VALUE

If the requested access is permitted, access() succeeds and shall return 0; otherwise, -1 shall be returned and errno shall be set to indicate the error.

ERRORS

The access() function shall fail if:

[EACCES] Permission bits of the file mode do not permit the requested access, or search permission is denied on a component of the path prefix.

[ELOOP] A loop exists in symbolic links encountered during resolution of the path argument.

[ENAMETOOLONG] The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

[ENOENT] A component of path does not name an existing file or path is an empty string.

[ENOTDIR] A component of the path prefix is not a directory.

[EROFS] Write access is requested for a file on a read-only file system.

Page 36: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The access() function may fail if:

[EINVAL] The value of the amode argument is invalid.

[ELOOP] More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.

[ENAMETOOLONG] As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

[ETXTBSY] Write access is requested for a pure procedure (shared text) file that is being executed.

EXAMPLES

Testing for the Existence of a File

The following example tests whether a file named myfile exists in the /tmp directory.

#include <unistd.h> ... int result; const char *filename = "/tmp/myfile"; result = access (filename, F_OK);

NAME chmod - change mode of a file

SYNOPSIS #include <sys/stat.h> int chmod(const char *path, mode_tmode);

DESCRIPTION

The chmod() function shall change S_ISUID, S_ISGID, S_ISVTX, and the file permission bits of the file named by the pathname pointed to by the path argument to the corresponding bits in the mode argument. The application shall ensure that the effective user ID of the process matches the owner of the file or the process has appropriate privileges in order to do this.

S_ISUID, S_ISGID, S_ISVTX, and the file permission bits are described in <sys/stat.h>.

If the calling process does not have appropriate privileges, and if the group ID of the file does not match the effective group ID or one of the supplementary group IDs and if the file is a

Page 37: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

regular file, bit S_ISGID (set-group-ID on execution) in the file's mode shall be cleared upon successful return from chmod().

Additional implementation-defined restrictions may cause the S_ISUID and S_ISGID bits in mode to be ignored.

The effect on file descriptors for files open at the time of a call to chmod() is implementation-defined.

Upon successful completion, chmod() shall mark for update the st_ctime field of the file.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error. If -1 is returned, no change to the file mode occurs.

ERRORS

The chmod() function shall fail if:

[EACCES] Search permission is denied on a component of the path prefix.

[ELOOP] A loop exists in symbolic links encountered during resolution of the path argument.

[ENAMETOOLONG] The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

[ENOTDIR] A component of the path prefix is not a directory.

[ENOENT] A component of path does not name an existing file or path is an empty string.

[EPERM] The effective user ID does not match the owner of the file and the process does not have appropriate privileges.

[EROFS] The named file resides on a read-only file system.

The chmod() function may fail if:

[EINTR] A signal was caught during execution of the function.

[EINVAL] The value of the mode argument is invalid.

[ELOOP] More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.

Page 38: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

[ENAMETOOLONG] As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname strings exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Setting Read Permissions for User, Group, and Others

The following example sets read permissions for the owner, group, and others.

#include <sys/stat.h> const char *path; ... chmod(path, S_IRUSR|S_IRGRP|S_IROTH);

Setting Read, Write, and Execute Permissions for the Owner Only

The following example sets read, write, and execute permissions for the owner, and no permissions for group and others.

#include <sys/stat.h> const char *path; ... chmod(path, S_IRWXU);

Setting Different Permissions for Owner, Group, and Other

The following example sets owner permissions for CHANGEFILE to read, write, and execute, group permissions to read and execute, and other permissions to read.

#include <sys/stat.h>

#define CHANGEFILE "/etc/myfile" ... chmod(CHANGEFILE, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);

Page 39: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Setting and Checking File Permissions

The following example sets the file permission bits for a file named /home/cnd/mod1, then calls the stat() function to verify the permissions.

#include <sys/types.h> #include <sys/stat.h> int status; struct stat buffer ... chmod("home/cnd/mod1", S_IRWXU|S_IRWXG|S_IROTH|S_IWOTH); status = stat("home/cnd/mod1", &buffer;);

NAME chmod - change the file modes

SYNOPSIS

chmod[-R]mode file...

DESCRIPTION

The chmod utility shall change any or all of the file mode bits of the file named by each file operand in the way specified by the mode operand.

It is implementation-defined whether and how the chmod utility affects any alternate or additional file access control mechanism (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.4, File Access Permissions) being used for the specified file.

Only a process whose effective user ID matches the user ID of the file, or a process with the appropriate privileges, shall be permitted to change the file mode bits of a file.

OPTIONS

The chmod utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-R Recursively change file mode bits. For each file operand that names a directory, chmod shall change the file mode bits of the directory and all files in the file hierarchy below it.

Page 40: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

OPERANDS

The following operands shall be supported:

mode Represents the change to be made to the file mode bits of each file named by one of the file operands; see the EXTENDED DESCRIPTION section.

file A pathname of a file whose file mode bits shall be modified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of chmod:

LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)

LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables.

LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).

LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.

NLSPATH [XSI] Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

Page 41: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The mode operand shall be either a symbolic_mode expression or a non-negative octal integer. The symbolic_mode form is described by the grammar later in this section.

Each clause shall specify an operation to be performed on the current file mode bits of each file. The operations shall be performed on each file in the order in which the clauses are specified.

The who symbols u, g, and o shall specify the user, group, and other parts of the file mode bits, respectively. A who consisting of the symbol a shall be equivalent to ugo.

The perm symbols r, w, and x represent the read, write, and execute/ search portions of file mode bits, respectively. The perm symbol s shall represent the set-user-ID-on-execution (when who contains or implies u) and set-group-ID-on-execution (when who contains or implies g) bits.

The perm symbol X shall represent the execute/search portion of the file mode bits if the file is a directory or if the current (unmodified) file mode bits have at least one of the execute bits (S_IXUSR, S_IXGRP, or S_IXOTH) set. It shall be ignored if the file is not a directory and none of the execute bits are set in the current file mode bits.

The permcopy symbols u, g, and o shall represent the current permissions associated with the user, group, and other parts of the file mode bits, respectively. For the remainder of this section, perm refers to the non-terminals perm and permcopy in the grammar.

If multiple actionlists are grouped with a single wholist in the grammar, each actionlist shall be applied in the order specified with that wholist. The op symbols shall represent the operation performed, as follows:

+ If perm is not specified, the '+' operation shall not change the file mode bits.

Page 42: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be set.

Otherwise, the file mode bits represented by the specified who and perm values shall be set.

- If perm is not specified, the '-' operation shall not change the file mode bits.

If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be cleared.

Otherwise, the file mode bits represented by the specified who and perm values shall be cleared.

= Clear the file mode bits specified by the who value, or, if no who value is specified, all of the file mode bits specified in this volume of IEEE Std 1003.1-2001.

If perm is not specified, the '=' operation shall make no further modifications to the file mode bits.

If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be set.

Otherwise, the file mode bits represented by the specified who and perm values shall be set.

When using the symbolic mode form on a regular file, it is implementation-defined whether or not:

• Requests to set the set-user-ID-on-execution or set-group-ID-on-execution bit when all execute bits are currently clear and none are being set are ignored.

• Requests to clear all execute bits also clear the set-user-ID-on-execution and set-group-ID-on-execution bits.

• Requests to clear the set-user-ID-on-execution or set-group-ID-on-execution bits when all execute bits are currently clear are ignored. However, if the command ls-lfile writes an s in the position indicating that the set-user-ID-on-execution or set-group-ID-on-execution is set, the commands chmodu-sfile or chmodg-sfile, respectively, shall not be ignored.

Page 43: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

When using the symbolic mode form on other file types, it is implementation-defined whether or not requests to set or clear the set-user-ID-on-execution or set-group-ID-on-execution bits are honored.

If the who symbol o is used in conjunction with the perm symbol s with no other who symbols being specified, the set-user-ID-on-execution and set-group-ID-on-execution bits shall not be modified. It shall not be an error to specify the who symbol o in conjunction with the perm symbol s.

[XSI] The perm symbol t shall specify the S_ISVTX bit. When used with a file of type directory, it can be used with the who symbol a, or with no who symbol. It shall not be an error to specify a who symbol of u, g, or o in conjunction with the perm symbol t, but the meaning of these combinations is unspecified. The effect when using the perm symbol t with any file type other than directory is unspecified.

For an octal integer mode operand, the file mode bits shall be set absolutely.

For each bit set in the octal number, the corresponding file permission bit shown in the following table shall be set; all other file permission bits shall be cleared. For regular files, for each bit set in the octal number corresponding to the set-user-ID-on-execution or the set-group-ID-on-execution, bits shown in the following table shall be set; if these bits are not set in the octal number, they are cleared. For other file types, it is implementation-defined whether or not requests to set or clear the set-user-ID-on-execution or set-group-ID-on-execution bits are honored.

Octal Mode Bit Octal Mode Bit Octal Mode Bit Octal Mode Bit

4000 S_ISUID 0400 S_IRUSR 0040 S_IRGRP 0004 S_IROTH

2000 S_ISGID 0200 S_IWUSR 0020 S_IWGRP 0002 S_IWOTH

1000 S_ISVTX 0100 S_IXUSR 0010 S_IXGRP 0001 S_IXOTH

When bits are set in the octal number other than those listed in the table above, the behavior is unspecified.

Grammar for chmod

The grammar and lexical conventions in this section describe the syntax for the symbolic_mode operand. The general conventions for this style of grammar are described in Grammar Conventions. A valid symbolic_mode can be represented as the non-terminal symbol symbolic_mode in the grammar. This formal syntax shall take precedence over the preceding text syntax description.

The lexical processing is based entirely on single characters. Implementations need not allow <blank>s within the single argument being processed.

Page 44: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

%start symbolic_mode %% symbolic_mode : clause | symbolic_mode ',' clause ; clause : actionlist | wholist actionlist ; wholist : who | wholist who ; who : 'u' | 'g' | 'o' | 'a' ; actionlist : action | actionlist action ; action : op | op permlist | op permcopy ; permcopy : 'u' | 'g' | 'o' ; op : '+' | '-' | '=' ; permlist : perm | perm permlist ;

Page 45: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

[XSI] perm : 'r' | 'w' | 'x' | 'X' | 's' | 't' ;

EXIT STATUS

The following exit values shall be returned:

0 The utility executed successfully and all requested changes were made.

>0 An error occurred.

CONSEQUENCES OF ERRORS

Default.

NAME fchmod - change mode of a file

SYNOPSIS

#include <sys/stat.h> int fchmod(intfildes, mode_tmode);

DESCRIPTION

The fchmod() function shall be equivalent to chmod() except that the file whose permissions are changed is specified by the file descriptor fildes.

• If fildes references a shared memory object, the fchmod() function need only affect the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits.

• If fildes references a typed memory object, the behavior of fchmod() is unspecified. • If fildes refers to a socket, the behavior of fchmod() is unspecified.

• If fildes refers to a STREAM (which is fattach()-ed into the file system name space) the call returns successfully, doing nothing.

Page 46: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

RETURN VALUE

Upon successful completion, fchmod() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.

EXAMPLES

Changing the Current Permissions for a File

The following example shows how to change the permissions for a file named /home/cnd/mod1 so that the owner and group have read/write/execute permissions, but the world only has read/write permissions.

#include <sys/stat.h> #include <fcntl.h> mode_t mode; int fildes; ... fildes = open("/home/cnd/mod1", O_RDWR); fchmod(fildes, S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH);

link function

NAME link - link to a file

SYNOPSIS

#include <unistd.h> int link(const char *path1, const char *path2);

DESCRIPTION

The link() function shall create a new link (directory entry) for the existing file, path1.

The path1 argument points to a pathname naming an existing file. The path2 argument points to a pathname naming the new directory entry to be created. The link() function shall atomically create a new link for the existing file and the link count of the file shall be incremented by one.

Page 47: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

If path1 names a directory, link() shall fail unless the process has appropriate privileges and the implementation supports using link() on directories.

Upon successful completion, link() shall mark for update the st_ctime field of the file. Also, the st_ctime and st_mtime fields of the directory that contains the new entry shall be marked for update.

If link() fails, no link shall be created and the link count of the file shall remain unchanged.

The implementation may require that the calling process has permission to access the existing file.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The link() function shall fail if:

[EACCES] A component of either path prefix denies search permission, or the requested link requires writing in a directory that denies write permission, or the calling process does not have permission to access the existing file and this is required by the implementation.

[EEXIST] The path2 argument resolves to an existing file or refers to a symbolic link.

[ELOOP] A loop exists in symbolic links encountered during resolution of the path1 or path2 argument.

[EMLINK] The number of links to the file named by path1 would exceed {LINK_MAX}.

[ENAMETOOLONG] The length of the path1 or path2 argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

[ENOENT] A component of either path prefix does not exist; the file named by path1 does not exist; or path1 or path2 points to an empty string.

[ENOSPC] The directory to contain the link cannot be extended.

[ENOTDIR] A component of either path prefix is not a directory.

[EPERM] The file named by path1 is a directory and either the calling process does not have appropriate privileges or the implementation prohibits using link() on directories.

[EROFS]

Page 48: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The requested link requires writing in a directory on a read-only file system. [EXDEV]

The link named by path2 and the file named by path1 are on different file systems and the implementation does not support links between file systems.

[EXDEV] [XSR] path1 refers to a named STREAM.

The link() function may fail if:

[ELOOP] More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path1 or path2 argument.

[ENAMETOOLONG] As a result of encountering a symbolic link in resolution of the path1 or path2 argument, the length of the substituted pathname string exceeded {PATH_MAX}.

EXAMPLES

Creating a Link to a File

The following example shows how to create a link to a file named /home/cnd/mod1 by creating a new directory entry named /modules/pass1.

#include <unistd.h> char *path1 = "/home/cnd/mod1"; char *path2 = "/modules/pass1"; int status;... status = link (path1, path2);

Creating a Link to a File Within a Program

In the following program example, the link() function links the /etc/passwd file (defined as PASSWDFILE) to a file named /etc/opasswd (defined as SAVEFILE), which is used to save the current password file. Then, after removing the current password file (defined as PASSWDFILE), the new password file is saved as the current password file using the link() function again.

#include <unistd.h>

#define LOCKFILE "/etc/ptmp" #define PASSWDFILE "/etc/passwd" #define SAVEFILE "/etc/opasswd" ... /* Save current password file */ link (PASSWDFILE, SAVEFILE);

Page 49: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

/* Remove current password file. */ unlink (PASSWDFILE); /* Save new password file as current password file. */ link (LOCKFILE,PASSWDFILE);

NAME

unlink - call the unlink function

SYNOPSIS

Unlink(file)

Description

The unlink utility shall perform the function call:

unlink(file);

A user may need appropriate privilege to invoke the unlink utility.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of unlink:

LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)

LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables.

LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).

LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.

NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES .

Page 50: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

NAME date - write the date and time

SYNOPSIS

date[-u] [+format]

DESCRIPTION

The date utility shall write the date and time to standard output [XSI] or attempt to set the system date and time. By default, the current date and time shall be written. If an operand beginning with '+' is specified, the output format of date shall be controlled by the conversion specifications and other text in the operand.

OPTIONS

The date utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-u Perform operations as if the TZ environment variable was set to the string "UTC0", or its equivalent historical value of "GMT0". Otherwise, date shall use the timezone indicated by the TZ environment variable or the system default if that variable is unset or null.

Conversion Specifications %a

Locale's abbreviated weekday name. %A

Locale's full weekday name. %b

Locale's abbreviated month name. %B

Locale's full month name. %c

Locale's appropriate date and time representation. %C

Century (a year divided by 100 and truncated to an integer) as a decimal number [00,99]. %d

Day of the month as a decimal number [01,31]. %D

Date in the format mm/dd/yy. %e

Day of the month as a decimal number [1,31] in a two-digit field with leading space character fill.

Page 51: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

%h A synonym for %b.

%H Hour (24-hour clock) as a decimal number [00,23].

%I Hour (12-hour clock) as a decimal number [01,12].

%j Day of the year as a decimal number [001,366].

%m Month as a decimal number [01,12].

%M Minute as a decimal number [00,59].

%n A <newline>.

%p Locale's equivalent of either AM or PM.

%r 12-hour clock time [01,12] using the AM/PM notation; in the POSIX locale, this shall be equivalent to %I : %M : %S%p.

%S Seconds as a decimal number [00,60].

%t A <tab>.

%T 24-hour clock time [00,23] in the format HH:MM:SS.

%u Weekday as a decimal number [1,7] (1=Monday).

%U Week of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday shall be considered to be in week 0.

%V Week of the year (Monday as the first day of the week) as a decimal number [01,53]. If the week containing January 1 has four or more days in the new year, then it shall be considered week 1; otherwise, it shall be the last week of the previous year, and the next week shall be week 1.

%w Weekday as a decimal number [0,6] (0=Sunday).

%W Week of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday shall be considered to be in week 0.

%x Locale's appropriate date representation.

%X Locale's appropriate time representation.

%y Year within century [00,99].

Page 52: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

%Y Year with century as a decimal number.

%Z Timezone name, or no characters if no timezone is determinable.

%% A percent sign character.

Setjump and longjump functions

NAME setjmp - set jump point for a non-local goto

SYNOPSIS

#include <setjmp.h> int setjmp(jmp_bufenv);

DESCRIPTION

A call to setjmp() shall save the calling environment in its env argument for later use by longjmp(). 

It is unspecified whether setjmp() is a macro or a function. If a macro definition is suppressed in order to access an actual function, or a program defines an external identifier with the name setjmp, the behavior is undefined.

An application shall ensure that an invocation of setjmp() appears in one of the following contexts only:

• The entire controlling expression of a selection or iteration statement • One operand of a relational or equality operator with the other operand an integral

constant expression, with the resulting expression being the entire controlling expression of a selection or iteration statement

• The operand of a unary '!' operator with the resulting expression being the entire controlling expression of a selection or iteration

• The entire expression of an expression statement (possibly cast to void)

If the invocation appears in any other context, the behavior is undefined.

RETURN VALUE

If the return is from a direct invocation, setjmp() shall return 0. If the return is from a call to longjmp(), setjmp() shall return a non-zero v

Page 53: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

NAME longjmp - non-local goto

SYNOPSIS

#include <setjmp.h> void longjmp(jmp_bufenv, intval);

DESCRIPTION

The longjmp() function shall restore the environment saved by the most recent invocation of setjmp() in the same thread, with the corresponding jmp_buf argument. If there is no such invocation, or if the function containing the invocation of setjmp() has terminated execution in the interim, or if the invocation of setjmp() was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined. [CX] It is unspecified whether longjmp() restores the signal mask, leaves the signal mask unchanged, or restores it to its value at the time setjmp() was called.

All accessible objects have values, and all other components of the abstract machine have state (for example, floating-point status flags and open files), as of the time longjmp() was called, except that the values of objects of automatic storage duration are unspecified if they meet all the following conditions:

• They are local to the function containing the corresponding setjmp() invocation. • They do not have volatile-qualified type. • They are changed between the setjmp() invocation and longjmp() call.

RETURN VALUE

After longjmp() is completed, program execution continues as if the corresponding invocation of setjmp() had just returned the value specified by val. The longjmp() function shall not cause setjmp() to return 0; if val is 0, setjmp() shall return 1.

Process Control

A process is basically a single running program. It may be a ``system'' program (e.g login, update, csh) or program initiated by the user (textedit, dbxtool or a user written one). When UNIX runs a process it gives each process a unique number - a process ID, pid. The UNIX command ps will list all current processes running on your machine and will list the pid. The C function int getpid() will return the pid of process that called this function. A program usually runs as a single process. However later we will see how we can make programs run as several separate communicating processes.

Page 54: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Running UNIX Commands from C

We can run commands from a C program just as if they were from the UNIX command line by using the system() function. NOTE: this can save us a lot of time and hassle as we can run other (proven) programs, scripts etc. to do set tasks.

int system(char *string) -- where string can be the name of a unix utility, an executable shell script or a user program. System returns the exit status of the shell. System is prototyped in <stdlib.h>

Example: Call ls from a program

main()

{ printf(``Files in Directory are: n''); system(``ls -l''); }

fork()

int fork() turns a single process into 2 identical processes, known as the parent and the child. On success, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. On failure, fork() returns -1 to the parent process, sets errno to indicate the error, and no child process is created.

NOTE: The child process will have its own unique PID.

The following program illustrates a simple use of fork, where two copies are made and run together (multitasking)

main() { int return_value;

printf(``Forking process n''); fork(); printf(``The process id is %d

and return value is %d n", getpid(), return_value); execl(``/bin/ls/'',``ls'',``-l'',0);

printf(``This line is not printed n''); }

Page 55: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The Output of this would be:

Forking process The process id is 6753 and return value is 0 The process id is 6754 and return value is 0 two lists of files in current directory

NOTE: The processes have unique ID's which will be different at each run.

Vfork

NAME

vfork - create a child process and block parent

SYNOPSIS

#include <sys/types.h> #include <unistd.h>

pid_t vfork(void);

STANDARD DESCRIPTION

(From XPG4 / SUSv2 / POSIX draft.) The vfork() function has the same effect as fork(), except that the behaviour is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.

LINUX DESCRIPTION

• vfork, just like fork(2), creates a child process of the calling process. For details and return value and errors, see fork(2).

• vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance sensitive applications where a child will be created which then immediately issues an execve().

Page 56: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

• vfork() differs from fork in that the parent is suspended until the child makes a call to execve(2) or _exit(2). The child shares all memory with its parent, including the stack, until execve() is issued by the child. The child must not return from the current function or call exit(), but may call _exit().

Signal handlers are inherited, but not shared. Signals to the parent arrive after the child releases the parent.

Wait and waitpid

NAME

wait, waitpid - wait for process termination

SYNOPSIS

#include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options);

DESCRIPTION

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed.

The waitpid function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed.

The value of pid can be one of:

< -1 which means to wait for any child process whose process group ID is equal to the absolute value of pid. -1 which means to wait for any child process; this is the same behaviour which wait exhibits. 0 which means to wait for any child process whose process group ID is equal to that of the calling process. > 0 which means to wait for the child whose process ID is equal to thevalue of pid.

Page 57: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The value of options is an OR of zero or more of the following constants: Exec

NAME exec - execute commands and open, close, or copy file descriptors

SYNOPSIS

exec[command[argument...]]

DESCRIPTION

The exec utility shall open, close, and/or copy file descriptors as specified by any redirections as part of the command.

If exec is specified without command or arguments, and any file descriptors with numbers greater than 2 are opened with associated redirection statements, it is unspecified whether those file descriptors remain open when the shell invokes another utility. Scripts concerned that child shells could misuse open file descriptors can always close them explicitly, as shown in one of the following examples.

If exec is specified with command, it shall replace the shell with command without creating a new process. If arguments are specified, they shall be arguments to command. Redirection affects the current shell execution environment.

EXAMPLES

Open readfile as file descriptor 3 for reading: exec 3< readfile Open writefile as file descriptor 4 for writing: exec 4> writefile Make file descriptor 5 a copy of file descriptor 0: exec 5<&0 Close file descriptor 3: exec 3<&- Cat the file maggie by replacing the current shell with the cat utility: exec cat maggie UNIT III

SIGNALS

Page 58: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Sending signals

• Typing certain key combinations at the controlling terminal of a running process causes the system to send it certain signals:

o Ctrl-C (in older Unixes, DEL) sends an INT signal (SIGINT); by default, this causes the process to terminate.

o Ctrl-Z sends a TSTP signal (SIGTSTP); by default, this causes the process to suspend execution.

o Ctrl-\ sends a QUIT signal (SIGQUIT); by default, this causes the process to terminate and dump core.

o (Those default key combinations can be changed with the stty command.) • The kill(2)system call will send the specified signal to the process, if permissions allow.

Similarly, the kill(1) command allows a user to send signals to processes. The raise(3) library function sends the specified signal to the current process.

• Exceptions such as division by zero or a segmentation violation will generate signals (here, SIGFPE and SIGSEGV respectively, which both by default cause a core dump and a program exit).

• The kernel can generate a signal to notify the process of an event. For example, SIGPIPE will be generated when a process writes to a pipe which has been closed by the reader; by default, this causes the process to terminate, which is convenient when constructing shell pipelines.

• Signal handlers can be installed with the signal() system call. If a signal handler is not installed for a particular signal, the default handler is used. Otherwise the signal is intercepted and the signal handler is invoked. The process can also specify two default behaviors, without creating a handler: ignore the signal (SIG_IGN) and use the default signal handler (SIG_DFL). There are two signals which cannot be intercepted and handled: SIGKILL and SIGSTOP.

• Signals can cause the interruption of a system call in progress, leaving it to the application to manage a non-transparent restart.

• Signal handlers should be written in a way that doesn't result in any unwanted side-effects, e.g. errno alteration, signal mask alteration, signal disposition change, and other global process attribute changes. Use of non-reentrant functions, e.g. malloc or printf, inside signal handlers is also unsafe

Relationship with hardware exceptions

A process's execution may result in the generation of a hardware exception, for instance, if the process attempts to divide by zero or incurs a TLB miss. In Unix-like operating systems, this event automatically changes the processor context to start executing a kernelexception handler. In case of some exceptions, such as a page fault, the kernel has sufficient information to fully handle the event itself and resume the process's execution. Other exceptions, however, the kernel cannot process intelligently and it must instead defer the exception handling operation to the faulting process. This deferral is achieved via the signal mechanism, wherein the kernel sends to the process a signal corresponding to the current exception. For example, if a process attempted to divide by zero on an x86CPU, a divide error exception would be generated and cause the kernel to send the SIGFPE signal to the process. Similarly, if the process attempted to access a memory address outside of its virtual address space, the kernel would notify the process of this

Page 59: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

violation via a SIGSEGV signal. The exact mapping between signal names and exceptions is obviously dependent upon the CPU, since exception types differ between architectures

POSIX signals

The list below documents the signals that are specified by the Single Unix Specification.[1] All signals are defined as macro constants in <signal.h> header file. The name of the macro constant consists of "SIG" prefix and several characters that identify the signal. Each macro constant expands into an integral number; these numbers can vary across platforms.

SIGABRT The SIGABRT signal is sent to a process to tell it to abort, i.e. to terminate. The signal can only be initiated by the process itself when it calls abort function of the C Standard Library.

SIGALRM, SIGVTALRM and SIGPROF The SIGALRM, SIGVTALRM and SIGPROF signal is sent to a process when the time limit specified in a call to a preceding alarm setting function (such as setitimer elapses. SIGALRM is sent when real or clock time elapses. SIGVTALRM is sent when CPU time used by the process elapses. SIGPROF is sent when CPU time used by the process and by the system on behalf of the process elapses.

SIGBUS The SIGBUS signal is sent to a process when it causes a bus error. The conditions that lead to the signal being raised are, for example, incorrect memory access alignment or non-existent physical address.

SIGCHLD The SIGCHLD signal is sent to a process when a child process terminates, is interrupted, or resumes after being interrupted. One common usage of the signal is to instruct the operating system to clean up the resources used by a child process after its termination without an explicit call to the wait system call.

SIGCONT The SIGCONT signal instructs the operating system to restart a process previously paused by the SIGSTOP or SIGTSTP signal. One important use of this signal is in job control in the Unix shell.

SIGFPE The SIGFPE signal is sent to a process when it executes an erroneous arithmetic operation, such as division by zero.

SIGHUP The SIGHUP signal is sent to a process when its controlling terminal is closed. It was originally designed to notify the process of a serial line drop. In modern systems, this signal usually means that controlling pseudo or virtual terminal has been closed.[2]

SIGILL The SIGILL signal is sent to a process when it attempts to execute a malformed, unknown, or privileged instruction.

SIGINT

Page 60: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Control-C, but on some systems, the "delete" character or "break" key can be used.[3]

SIGKILL The SIGKILL signal is sent to a process to cause it to terminate immediately. In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal.

SIGPIPE The SIGPIPE signal is sent to a process when it attempts to write to a pipe without a process connected to the other end.

SIGQUIT The SIGQUIT signal is sent to a process by its controlling terminal when the user requests that the process perform a core dump.

SIGSEGV The SIGSEGV signal is sent to a process when it makes an invalid virtual memory reference, or segmentation fault.

SIGSTOP The SIGSTOP signal instructs the operating system to stop a process for later resumption.

SIGTERM The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate.

SIGTSTP The SIGTSTP signal is sent to a process by its controlling terminal to request it to stop temporarily. It is commonly initiated by the user pressing Control-Z. Unlike SIGSTOP, the process can register a signal handler for or ignore the signal.

SIGTTIN and SIGTTOU The SIGTTIN and SIGTTOU signals are sent to a process when it attempts to read or write respectively from the tty while in the background. Typically, this signal can be received only by processes under job control; daemons do not have controlling terminals and should never receive this signal.

SIGUSR1 and SIGUSR2 The SIGUSR1 and SIGUSR2 signals are sent to a process to indicate user-defined conditions.

SIGPOLL The SIGPOLL signal is sent to a process when an asynchronous I/O event occurs.

SIGSYS The SIGSYS signal is sent to a process when it passes a bad argument to a system call.

SIGTRAP The SIGTRAP signal is sent to a process when a condition arises that a debugger has requested to be informed of — for example, when a particular function is executed, or when a particular variable changes value.

SIGURG The SIGURG signal is sent to a process when a socket has urgent data available to read.

SIGXCPU

Page 61: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The SIGXCPU signal is sent to a process when it has used up the CPU for a duration that exceeds a certain predetermined user-settable value. [4] The arrival of a SIGXCPU signal provides the receiving process a chance to quickly save any intermediate results and to exit gracefully, before it is terminated by the operating system using the SIGKILL signal.

SIGXFSZ The SIGXFSZ signal is sent to a process when it grows a file larger than the maximum allowed size.

SIGRTMIN to SIGRTMAX The SIGRTMIN to SIGRTMAX signals are intended to be used for user-defined purposes. They are real-time signals.

Signal Blocking

Signals represent a very limited form of interprocess communication. They are easy to use (hard to use well) but they communicate very little information. In addition the sender (if it is a process) and the receiver must belong to the same user id, or the sender must be the superuser. Signals are sent explicitly to a process from another process using the kill function. Signals can indicate some significant terminal action, such as Hang Up. Alternatively, signals are sent to a process from the hardware (to indicate things like illegal operator, or illegal address) through mediation of the OS. Beware that signals could also be caused by an internet connection, for example a TCP/IP OOB (out of band) message could cause the SIGURG signal. There are only a few possible signals (usually 32 - wait: I just checked on my GNU/Linux 2.6.17-1.2142_FC4 and I have now 64 possible signals!)). A process can specify with a mask (1 bit per signal) what it wants to be done with a signal directed to it, whether to block it or to deliver it. Blocked signals remain pending, i.e. we may ask to have them delivered later. A process specifies with the signal function (obsolete) or with the sigaction function what it wants it to be done when signals are delivered to it. When a signal is delivered to a process (i.e. it is not blocked), an action takes place. For each signal there is a default action specific to that signal. Or for a signal an action (a handler) can be specified by the program.

There are three actions that can take place when a signal is delivered to a process:

• it can be ignored; or • the process can be terminated (with or without core dumping); or • a handler function can be called. This function receives as its only argument the number

identifying the signal it is handling.

The association of a signal to an action remains in place until it is explicitly modified with a signal or sigaction call. [This is the behavior at least in modern Unix systems. In older Unix after each signal handling occurrence the handler reverted to the default handler. This created a race condition if we were intending to re-establish a non default handler. For this reason old Unix was said to be with unrelieable signals.] In writing a handler function one has to be conscious that it is executed as an asynchronous action during the execution of a process (well, there are also synchronous signals like SIGBUS due to the use of an illegal address). The handler code may execute a routine that was interrupted by the signal, or access variables that were being used in the process. Thus one has to be careful

Page 62: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

about the code that is executed in the handler and in the variables it accesses. [You may want to examine in C or C++ the use of the attribute volatile.] During execution of the handler associated to a signal, that specific signal is automatically blocked thus preventing a race condition. But beware that if the same handler is specified for two different signals A and B, then during the execution of the handler for A, a B signal will not be blocked and the handler will be reentered. After the handler function is completed, execution resumes at the statement being executed when the signal was received. If the signal occurred while the process was executing a system call, things become more comples. The system call may be terminated without completing and return the value EINTR. In some systems it is possible to specify that interrupted system calls be automatically restarted by using the flag SA_RESTART. In other system SA_RESTART is the default.

The following diagram describes how a signal is raised, possibly blocked before delivery, and then handled.

Here are some of the possible signals, with the number associated to them, and their default handling.

SIGNAL ID DEFAULT DESCRIPTION ====================================================================== SIGHUP 1 Termin. Hang up on controlling terminal SIGINT 2 Termin. Interrupt. Generated when we enter CNRTL-C and it is delivered to all processes/threads associated to the current terminal. If

Page 63: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

generated with kill, it is delivered to only one process/thread. SIGQUIT 3 Core Generated when at terminal we enter CNRTL-\ SIGILL 4 Core Generated when we executed an illegal instruction SIGTRAP 5 Core Trace trap (not reset when caught) SIGABRT 6 Core Generated by the abort function SIGFPE 8 Core Floating Point error SIGKILL 9 Termin. Termination (can't catch, block, ignore) SIGBUS 10 Core Generated in case of hardware fault SIGSEGV 11 Core Generated in case of illegal address SIGSYS 12 Core Generated when we use a bad argument in a system service call SIGPIPE 13 Termin. Generated when writing to a pipe or a socket while no process is reading at other end SIGALRM 14 Termin. Generated by clock when alarm expires SIGTERM 15 Termin. Software termination signal SIGURG 16 Ignore Urgent condition on IO channel SIGCHLD 20 Ignore A child process has terminated or stopped SIGTTIN 21 Stop Generated when a backgorund process reads from terminal SIGTTOUT 22 Stop Generated when a background process writes to terminal SIGXCPU 24 Discard CPU time has expired SIGUSR1 30 Termin. User defiled signal 1 SIGUSR2 31 Termin. User defined signal 2 The programmer can control (set or read) which signals are blocked [a blocked signal remains pending until the program unblocks that signal and the signal is delivered] with the sigprocmask function. #include <signal.h> int sigprocmask(int cmd, const sigset_t* new_mask, sigset_t* old_mask); where the parameter cmd can have the values SIG_SETMASK: sets the system mask to new_mask SIG_BLOCK: Adds the signals in new_mask to the system mask SIG_UNBLOCK: Removes the signals in new_mask from system mask

Here is an example of a program that uses sigaction and sigsuspend instead of signal and pause.

Since the use of signal is easier than the use of sigaction, Stevens suggests the use of the following definitions (slightly modified):

typedef void Sigfunc(int); /* Sigfunc is type of function with one int arg, and void return */ Sigfunc * signal(int signo, Sigfunc *func)

Page 64: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

{ struct sigaction act, oact; act.sa_handler = func; sigemptyset(&act.sa_mask); act.sa_flags = 0; #ifdef SA_RESTART if (signo != SIGALRM) act.sa_flags |= SA_RESTART; #endif if (sigaction(signo, &act, &oact) < 0) return (SIG_ERR); return (oact.sa_handler); }

UNIT IV IPC

In computing, Inter-process communication (IPC) is a set of methods for the exchange of data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC methods are divided into methods for message passing, synchronization, shared memory, and remote procedure calls (RPC). The method of IPC used may vary based on the bandwidth and latency of communication between the threads, and the type of data being communicated.

There are several reasons for providing an environment that allows process cooperation:

• Information sharing • Computational Speedup • Modularity • Convenience • Privilege separation

IPC may also be referred to as inter-thread communication and inter-application communication.

The combination of IPC with the address space concept is the foundation for address space independence/isolation.[

Main IPC methods Method Provided by (operating systems or other environments)

File Most operating systems

Signal Most operating systems; some systems, such as Windows, implement signals in only the C run-time library and provide no support for their use as an IPC method[citation needed]

Socket Most operating systems

Page 65: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

SRM Un

Message Pipe Named pSemaphoShared memory Message passing (shared nothing) Memory-mapped f PIPES

In computraditionaprocess csemanticand persiexists beyProcesseprocess c

U

iversity

queue MostAll P

pipe All Pore All P

All P

Used

-file All P

uting, a namal pipe concecommunicatis differ subsists only for yond the lifes generally a

communicati

Unix and

Depa

t operating sPOSIX systePOSIX systePOSIX syste

POSIX syste

d in MPI par

POSIX syste

med pipe (alsept on Unix ion. The constantially. A as long as th

e of the procattach to the ion (IPC).

d networ

artment of

systems ems, Windowems, Windowems, Window

ems, Window

radigm, Java

ems, Window

so known as and Unix-lik

ncept is also traditional p

he process iscess and mus

named pipe

rk Progr

Computer A

ws ws ws

ws

a RMI, CORB

ws

a FIFO for ke systems, found in Mi

pipe is "unnas running. A st be deleted es (usually ap

rammin

Application

BA, MSMQ

its behaviorand is one oicrosoft Winamed" becaunamed pipeonce it is no

ppearing as a

ng MC06

s S

Q, MailSlots,

r) is an extenof the methodndows, althouuse it exists ae is system-po longer beina file) to per

618  201

S.Kanchana

QNX, other

nsion to the ds of inter-ugh the anonymouslypersistent andng used. rform inter-

12 

Devi

rs

y d

Page 66: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Instead of a conventional, unnamed, shell pipeline, a named pipeline makes use of the filesystem. It is explicitly created using mkfifo() or mknod(), and two separate processes can access the pipe by name — one process can open it as a reader, and the other as a writer.

FIFO

Data structure

A typical data structure in the C++ language will look like

struct fifo_node { struct fifo_node *next; value_type value; }; class fifo { fifo_node *front; fifo_node *back; fifo_node *dequeue(void) { fifo_node *tmp = front; if( front != NULL ) front = front->next; else back = NULL; return tmp; } queue(value) { fifo_node *tempNode = new fifo_node; tempNode->value = value; if( front == NULL ) { front = tempNode; back = tempNode; } else { back->next = tempNode; back = tempNode; } }

Page 67: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

A named pipe can be used to transfer information from one application to another without the use of an intermediate temporary file. For example you can pipe the output of gzip into a named pipe like so:

mkfifo --mode=0666 /tmp/namedPipe gzip --stdout -d file.gz > /tmp/namedPipe

Then load the uncompressed data into a MySQL table[1] like so:

LOAD DATA INFILE '/tmp/namedPipe' INTO TABLE tableName;

Without this named pipe one would need to write out the entire uncompressed version of file.gz before loading it into MySQL. Writing the temporary file is both time consuming and results in more I/O and less free space on the hard drive.

PostgreSQL's command line terminal, psql, also supports loading data from named pipes

PIPELINE

In Unix-like computer operating systems (and, to some extent, Microsoft Windows), a pipeline is the original software pipeline: a set of processes chained by their standard streams, so that the output of each process (stdout) feeds directly as input (stdin) to the next one. Each connection is implemented by an anonymous pipe. Filter programs are often used in this configuration.

The concept was invented by Douglas McIlroy for Unix shells and it was named by analogy to a physical pipeline.[1]

Unix pipeline can be thought of as left associativeinfix operation whose operands are programs with parameters. Programatically all programs in pipeline run at the same time (in parallel), but, looking at syntax, it can be thought that one runs after another. It is a functional composition. One can be reminded of functional programming, where data is passed from one function to another (as their input or output).

FIFO

NAME mkfifo - make FIFO special files

SYNOPSIS

mkfifo[-mmode]file...

Page 68: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

DESCRIPTION

The mkfifo utility shall create the FIFO special files specified by the operands, in the order specified.

For each file operand, the mkfifo utility shall perform actions equivalent to the mkfifo() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

1. The file operand is used as the path argument. 2. The value of the bitwise-inclusive OR of S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP,

S_IROTH, and S_IWOTH is used as the mode argument. (If the -m option is specified, the value of the mkfifo()mode argument is unspecified, but the FIFO shall at no time have permissions less restrictive than the -mmode option-argument.)

NAME mkfifo - make a FIFO special file

SYNOPSIS

#include <sys/stat.h> int mkfifo(const char *path, mode_tmode);

DESCRIPTION

The mkfifo() function shall create a new FIFO special file named by the pathname pointed to by path. The file permission bits of the new FIFO shall be initialized from mode. The file permission bits of the mode argument shall be modified by the process' file creation mask.

When bits in mode other than the file permission bits are set, the effect is implementation-defined.

If path names a symbolic link, mkfifo() shall fail and set errno to [EEXIST].

The FIFO's user ID shall be set to the process' effective user ID. The FIFO's group ID shall be set to the group ID of the parent directory or to the effective group ID of the process. Implementations shall provide a way to initialize the FIFO's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the FIFO's group ID to the effective group ID of the calling process.

Upon successful completion, mkfifo() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file. Also, the st_ctime and st_mtime fields of the directory that contains the new entry shall be marked for update.

Page 69: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned, no FIFO shall be created, and errno shall be set to indicate the error.

ERRORS

The mkfifo() function shall fail if:

[EACCES] A component of the path prefix denies search permission, or write permission is denied on the parent directory of the FIFO to be created.

[EEXIST] The named file already exists.

[ELOOP] A loop exists in symbolic links encountered during resolution of the path argument.

[ENAMETOOLONG] The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

[ENOENT] A component of the path prefix specified by path does not name an existing directory or path is an empty string.

[ENOSPC] The directory that would contain the new file cannot be extended or the file system is out of file-allocation resources.

[ENOTDIR] A component of the path prefix is not a directory.

[EROFS] The named file resides on a read-only file system.

The mkfifo() function may fail if:

[ELOOP] More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.

[ENAMETOOLONG] As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

EXAMPLES

Creating a FIFO File

The following example shows how to create a FIFO file named /home/cnd/mod_done, with read/write permissions for owner, and with read permissions for group and others.

Page 70: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

#include <sys/types.h> #include <sys/stat.h> int status; ... status = mkfifo("/home/cnd/mod_done", S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);

IPC:Message Queues:<sys/msg.h> The basic idea of a message queue is a simple one. Two (or more) processes can exchange information via access to a common system message queue. The sending process places via some (OS) message-passing module a message onto a queue which can be read by another process (Figure 24.1). Each message is given an identification or type so that processes can select the appropriate message. Process must share a common key in order to gain access to the queue in the first place (subject to other permissions -- see below

Fig. Basic Message Passing

IPC messaging lets processes send and receive messages, and queue messages for processing in an arbitrary order. Unlike the file byte-stream data flow of pipes, each IPC message has an explicit length. Messages can be assigned a specific type. Because of this, a server process can direct message traffic between clients on its queue by using the client process PID as the message type. For single-message transactions, multiple server processes can work in parallel on transactions sent to a shared message queue.

Page 71: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Before a process can send or receive a message, the queue must be initialized (through the msgget function see below) Operations to send and receive messages are performed by the msgsnd() and msgrcv() functions, respectively.

When a message is sent, its text is copied to the message queue. The msgsnd() and msgrcv() functions can be performed as either blocking or non-blocking operations. Non-blocking operations allow for asynchronous message transfer -- the process is not suspended as a result of sending or receiving a message. In blocking or synchronous message passing the sending process cannot continue until the message has been transferred or has even been acknowledged by a receiver. IPC signal and other mechanisms can be employed to implement such transfer. A blocked message operation remains suspended until one of the following three conditions occurs:

• The call succeeds. • The process receives a signal. • The queue is removed

Initialising the Message Queue

The msgget() function initializes a new message queue:

int msgget(key_t key, int msgflg)

It can also return the message queue ID (msqid) of the queue corresponding to the key argument. The value passed as the msgflg argument must be an octal integer with settings for the queue's permissions and control flags.

The following code illustrates the msgget() function.

#include <sys/ipc.h>; #include <sys/msg.h>; key_t key; /* key to be passed to msgget() */ int msgflg /* msgflg to be passed to msgget() */ int msqid; /* return value from msgget() */ ... key = ... msgflg = ... if ((msqid = msgget(key, msgflg)) == &ndash;1) { perror("msgget: msgget failed"); exit(1); } else (void) fprintf(stderr, &ldquo;msgget succeeded"); ...

Page 72: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

IPC Functions, Key Arguments, and Creation Flags: <sys/ipc.h>

Processes requesting access to an IPC facility must be able to identify it. To do this, functions that initialize or provide access to an IPC facility use a key_t key argument. (key_t is essentially an int type defined in <sys/types.h>

The key is an arbitrary value or one that can be derived from a common seed at run time. One way is with ftok() , which converts a filename to a key value that is unique within the system. Functions that initialize or get access to messages (also semaphores or shared memory see later) return an ID number of type int. IPC functions that perform read, write, and control operations use this ID. If the key argument is specified as IPC_PRIVATE, the call initializes a new instance of an IPC facility that is private to the creating process. When the IPC_CREAT flag is supplied in the flags argument appropriate to the call, the function tries to create the facility if it does not exist already. When called with both the IPC_CREAT and IPC_EXCL flags, the function fails if the facility already exists. This can be useful when more than one process might attempt to initialize the facility. One such case might involve several server processes having access to the same facility. If they all attempt to create the facility with IPC_EXCL in effect, only the first attempt succeeds. If neither of these flags is given and the facility already exists, the functions to get access simply return the ID of the facility. If IPC_CREAT is omitted and the facility is not already initialized, the calls fail. These control flags are combined, using logical (bitwise) OR, with the octal permission modes to form the flags argument. For example, the statement below initializes a new message queue if the queue does not exist.

msqid = msgget(ftok("/tmp", key), (IPC_CREAT | IPC_EXCL | 0400));

The first argument evaluates to a key based on the string ("/tmp"). The second argument evaluates to the combined permissions and control flags.

Controlling message queues

The msgctl() function alters the permissions and other characteristics of a message queue. The owner or creator of a queue can change its ownership or permissions using msgctl() Also, any process with permission to do so can use msgctl() for control operations.

The msgctl() function is prototypes as follows:

int msgctl(int msqid, int cmd, struct msqid_ds *buf )

The msqid argument must be the ID of an existing message queue. The cmd argument is one of:

IPC_STAT -- Place information about the status of the queue in the data structure pointed to by buf. The process must have read permission for this call to succeed.

IPC_SET

Page 73: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

-- Set the owner's user and group ID, the permissions, and the size (in number of bytes) of the message queue. A process must have the effective user ID of the owner, creator, or superuser for this call to succeed.

IPC_RMID -- Remove the message queue specified by the msqid argument.

The following code illustrates the msgctl() function with all its various flags:

#include<sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> ... if (msgctl(msqid, IPC_STAT, &buf) == -1) { perror("msgctl: msgctl failed"); exit(1); } ... if (msgctl(msqid, IPC_SET, &buf) == -1) { perror("msgctl: msgctl failed"); exit(1); }

... Sending and Receiving Messages

The msgsnd() and msgrcv() functions send and receive messages, respectively:

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

The msqid argument must be the ID of an existing message queue. The msgp argument is a pointer to a structure that contains the type of the message and its text. The structure below is an example of what this user-defined buffer might look like:

struct mymsg { long mtype; /* message type */ char mtext[MSGSZ]; /* message text of length MSGSZ */ }

The msgsz argument specifies the length of the message in bytes.

The structure member msgtype is the received message's type as specified by the sending process.

Page 74: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The argument msgflg specifies the action to be taken if one or more of the following are true:

• The number of bytes already on the queue is equal to msg_qbytes. • The total number of messages on all queues system-wide is equal to the system-imposed limit.

These actions are as follows:

• If (msgflg & IPC_NOWAIT) is non-zero, the message will not be sent and the calling process will return immediately. • If (msgflg & IPC_NOWAIT) is 0, the calling process will suspend execution until one of the following occurs:

o The condition responsible for the suspension no longer exists, in which case the message is sent. o The message queue identifier msqid is removed from the system; when this occurs, errno is set equal to EIDRM and -1 is returned. o The calling process receives a signal that is to be caught; in this case the message is not sent and the calling process resumes execution.

Upon successful completion, the following actions are taken with respect to the data structure associated with msqid:

o msg_qnum is incremented by 1. o msg_lspid is set equal to the process ID of the calling process. o msg_stime is set equal to the current time.

The following code illustrates msgsnd() and msgrcv():

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> ... int msgflg; /* message flags for the operation */ struct msgbuf *msgp; /* pointer to the message buffer */ int msgsz; /* message size */ long msgtyp; /* desired message type */ int msqid /* message queue ID to be used */ ... msgp = (struct msgbuf *)malloc((unsigned)(sizeof(struct msgbuf) - sizeof msgp->mtext + maxmsgsz)); if (msgp == NULL) {

Page 75: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

(void) fprintf(stderr, "msgop: %s %d byte messages.\n", "could not allocate message buffer for", maxmsgsz); exit(1); ... msgsz = ... msgflg = ... if (msgsnd(msqid, msgp, msgsz, msgflg) == -1) perror("msgop: msgsnd failed"); ... msgsz = ... msgtyp = first_on_queue; msgflg = ... if (rtrn = msgrcv(msqid, msgp, msgsz, msgtyp, msgflg) == -1) perror("msgop: msgrcv failed"); ...

POSIX Messages: <mqueue.h>

The POSIX message queue functions are:

mq_open() -- Connects to, and optionally creates, a named message queue.

mq_close() -- Ends the connection to an open message queue.

mq_unlink() -- Ends the connection to an open message queue and causes the queue to be removed when the last process closes it.

mq_send() -- Places a message in the queue.

mq_receive() -- Receives (removes) the oldest, highest priority message from the queue.

mq_notify() -- Notifies a process or thread that a message is available in the queue.

mq_setattr() -- Set or get message queue attributes.

The basic operation of these functions is as described above. For full function prototypes and further information see the UNIX man pages

Example: Sending messages between two processes

The following two programs should be compiled and run at the same time to illustrate basic principle of message passing:

message_send.c

Page 76: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

-- Creates a message queue and sends one message to the queue. message_rec.c

-- Reads the message from the queue. message_send.c -- creating and sending to a simple message queue

The full code listing for message_send.c is as follows:

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h> #define MSGSZ 128 /* * Declare the message structure. */ typedef struct msgbuf { long mtype; char mtext[MSGSZ]; } message_buf; main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; message_buf sbuf; size_t buf_length; /* * Get the message queue id for the * "name" 1234, which was created by * the server. */ key = 1234;

(void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx,\ %#o)\n", key, msgflg); if ((msqid = msgget(key, msgflg )) < 0) { perror("msgget");

Page 77: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

exit(1); } else (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); /* * We'll send message type 1 */ sbuf.mtype = 1; (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); (void) strcpy(sbuf.mtext, "Did you get this?"); (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); buf_length = strlen(sbuf.mtext) + 1 ; /* * Send a message. */ if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length); perror("msgsnd"); exit(1); } else printf("Message: \"%s\" Sent\n", sbuf.mtext); exit(0); }

The essential points to note here are:

• The Message queue is created with a basic key and message flag msgflg = IPC_CREAT | 0666 -- create queue and make it read and appendable by all. • A message of type (sbuf.mtype) 1 is sent to the queue with the message ``Did you get this?''

Page 78: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

message_rec.c -- receiving the above message

The full code listing for message_send.c's companion process, message_rec.c is as follows:

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #define MSGSZ 128 /* * Declare the message structure. */ typedef struct msgbuf { long mtype; char mtext[MSGSZ]; } message_buf; main() { int msqid; key_t key; message_buf rbuf; /* * Get the message queue id for the * "name" 1234, which was created by * the server. */ key = 1234; if ((msqid = msgget(key, 0666)) < 0) { perror("msgget"); exit(1); }

/ * Receive an answer of message type 1. */ if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) { perror("msgrcv"); exit(1);

Page 79: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

} /* * Print the answer. */ printf("%s\n", rbuf.mtext); exit(0); }

The essential points to note here are:

• The Message queue is opened with msgget (message flag 0666) and the samekey as message_send.c. • A message of the same type 1 is received from the queue with the message ``Did you get this?'' stored in rbuf.mtext.

Some further example message queue programs

The following suite of programs can be used to investigate interactively a variety of massage passing ideas (see exercises below).

The message queue must be initialised with the msgget.c program. The effects of controlling the queue and sending and receiving messages can be investigated with msgctl.c and msgop.c respectively.

msgget.c: Simple Program to illustrate msget() /* * msgget.c: Illustrate the msgget() function. * This is a simple exerciser of the msgget() function. It prompts * for the arguments, makes the call, and reports the results. */ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> extern void exit(); extern void perror(); main() { key_t key; /* key to be passed to msgget() */ int msgflg, /* msgflg to be passed to msgget() */ msqid; /* return value from msgget() */

Page 80: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

(void) fprintf(stderr, "All numeric input is expected to follow C conventions:\n"); (void) fprintf(stderr, "\t0x... is interpreted as hexadecimal,\n"); (void) fprintf(stderr, "\t0... is interpreted as octal,\n"); (void) fprintf(stderr, "\totherwise, decimal.\n"); (void) fprintf(stderr, "IPC_PRIVATE == %#lx\n", IPC_PRIVATE); (void) fprintf(stderr, "Enter key: "); (void) scanf("%li", &key); (void) fprintf(stderr, "\nExpected flags for msgflg argument are:\n"); (void) fprintf(stderr, "\tIPC_EXCL =\t%#8.8o\n", IPC_EXCL); (void) fprintf(stderr, "\tIPC_CREAT =\t%#8.8o\n", IPC_CREAT); (void) fprintf(stderr, "\towner read =\t%#8.8o\n", 0400); (void) fprintf(stderr, "\towner write =\t%#8.8o\n", 0200); (void) fprintf(stderr, "\tgroup read =\t%#8.8o\n", 040); (void) fprintf(stderr, "\tgroup write =\t%#8.8o\n", 020); (void) fprintf(stderr, "\tother read =\t%#8.8o\n", 04); (void) fprintf(stderr, "\tother write =\t%#8.8o\n", 02); (void) fprintf(stderr, "Enter msgflg value: "); (void) scanf("%i", &msgflg); (void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx, %#o)\n", key, msgflg); if ((msqid = msgget(key, msgflg)) == -1) { perror("msgget: msgget failed"); exit(1); } else { (void) fprintf(stderr, "msgget: msgget succeeded: msqid = %d\n", msqid); exit(0); } } msgctl.cSample Program to Illustrate msgctl() /* * msgctl.c: Illustrate the msgctl() function. * * This is a simple exerciser of the msgctl() function. It allows * you to perform one control operation on one message queue. It * gives up immediately if any control operation fails, so be careful * not to set permissions to preclude read permission; you won't be * able to reset the permissions with this code if you do.

Page 81: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

*/ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <time.h> static void do_msgctl(); extern void exit(); extern void perror(); static char warning_message[] = "If you remove read permission for \ yourself, this program will fail frequently!"; main() { struct msqid_ds buf; /* queue descriptor buffer for IPC_STAT and IP_SET commands */ int cmd, /* command to be given to msgctl() */ msqid; /* queue ID to be given to msgctl() */ (void fprintf(stderr, "All numeric input is expected to follow C conventions:\n"); (void) fprintf(stderr, "\t0x... is interpreted as hexadecimal,\n"); (void) fprintf(stderr, "\t0... is interpreted as octal,\n"); (void) fprintf(stderr, "\totherwise, decimal.\n"); /* Get the msqid and cmd arguments for the msgctl() call. */ (void) fprintf(stderr, "Please enter arguments for msgctls() as requested."); (void) fprintf(stderr, "\nEnter the msqid: "); (void) scanf("%i", &msqid); (void) fprintf(stderr, "\tIPC_RMID = %d\n", IPC_RMID); (void) fprintf(stderr, "\tIPC_SET = %d\n", IPC_SET); (void) fprintf(stderr, "\tIPC_STAT = %d\n", IPC_STAT); (void) fprintf(stderr, "\nEnter the value for the command: "); (void) scanf("%i", &cmd); switch (cmd) { case IPC_SET: /* Modify settings in the message queue control structure. */ (void) fprintf(stderr, "Before IPC_SET, get current values:"); /* fall through to IPC_STAT processing */

Page 82: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

case IPC_STAT: /* Get a copy of the current message queue control * structure and show it to the user. */ do_msgctl(msqid, IPC_STAT, &buf); (void) fprintf(stderr, ] "msg_perm.uid = %d\n", buf.msg_perm.uid); (void) fprintf(stderr, "msg_perm.gid = %d\n", buf.msg_perm.gid); (void) fprintf(stderr, "msg_perm.cuid = %d\n", buf.msg_perm.cuid); (void) fprintf(stderr, "msg_perm.cgid = %d\n", buf.msg_perm.cgid); (void) fprintf(stderr, "msg_perm.mode = %#o, ", buf.msg_perm.mode); (void) fprintf(stderr, "access permissions = %#o\n", buf.msg_perm.mode & 0777); (void) fprintf(stderr, "msg_cbytes = %d\n", buf.msg_cbytes); (void) fprintf(stderr, "msg_qbytes = %d\n", buf.msg_qbytes); (void) fprintf(stderr, "msg_qnum = %d\n", buf.msg_qnum); (void) fprintf(stderr, "msg_lspid = %d\n", buf.msg_lspid); (void) fprintf(stderr, "msg_lrpid = %d\n", buf.msg_lrpid); (void) fprintf(stderr, "msg_stime = %s", buf.msg_stime ? ctime(&buf.msg_stime) : "Not Set\n"); (void) fprintf(stderr, "msg_rtime = %s", buf.msg_rtime ? ctime(&buf.msg_rtime) : "Not Set\n"); (void) fprintf(stderr, "msg_ctime = %s", ctime(&buf.msg_ctime)); if (cmd == IPC_STAT) break; /* Now continue with IPC_SET. */ (void) fprintf(stderr, "Enter msg_perm.uid: "); (void) scanf ("%hi", &buf.msg_perm.uid); (void) fprintf(stderr, "Enter msg_perm.gid: "); (void) scanf("%hi", &buf.msg_perm.gid); (void) fprintf(stderr, "%s\n", warning_message); (void) fprintf(stderr, "Enter msg_perm.mode: "); (void) scanf("%hi", &buf.msg_perm.mode); (void) fprintf(stderr, "Enter msg_qbytes: "); (void) scanf("%hi", &buf.msg_qbytes); do_msgctl(msqid, IPC_SET, &buf); break; case IPC_RMID:

Page 83: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

default: /* Remove the message queue or try an unknown command. */ do_msgctl(msqid, cmd, (struct msqid_ds *)NULL); break; } exit(0); } /* * Print indication of arguments being passed to msgctl(), call * msgctl(), and report the results. If msgctl() fails, do not * return; this example doesn't deal with errors, it just reports * them. */ static void do_msgctl(msqid, cmd, buf) struct msqid_ds *buf; /* pointer to queue descriptor buffer */ int cmd, /* command code */ msqid; /* queue ID */ { register int rtrn; /* hold area for return value from msgctl() */ (void) fprintf(stderr, "\nmsgctl: Calling msgctl(%d, %d, %s)\n", msqid, cmd, buf ? "&buf" : "(struct msqid_ds *)NULL"); rtrn = msgctl(msqid, cmd, buf); if (rtrn == -1) { perror("msgctl: msgctl failed"); exit(1); } else { (void) fprintf(stderr, "msgctl: msgctl returned %d\n", rtrn); } } msgop.c: Sample Program to Illustrate msgsnd() and msgrcv() /* * msgop.c: Illustrate the msgsnd() and msgrcv() functions. * * This is a simple exerciser of the message send and receive * routines. It allows the user to attempt to send and receive as many * messages as wanted to or from one message queue. #include <stdio.h> #include <sys/types.h>

Page 84: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

#include <sys/ipc.h> #include <sys/msg.h> static int ask(); extern void exit(); extern char *malloc(); extern void perror(); char first_on_queue[] = "-> first message on queue", full_buf[] = "Message buffer overflow. Extra message text\ discarded."; main() { register int c; /* message text input */ int choice; /* user's selected operation code */ register int i; /* loop control for mtext */ int msgflg; /* message flags for the operation */ struct msgbuf *msgp; /* pointer to the message buffer */ int msgsz; /* message size */ long msgtyp; /* desired message type */ int msqid, /* message queue ID to be used */ maxmsgsz, /* size of allocated message buffer */ rtrn; /* return value from msgrcv or msgsnd */ (void) fprintf(stderr, "All numeric input is expected to follow C conventions:\n"); (void) fprintf(stderr, "\t0x... is interpreted as hexadecimal,\n"); (void) fprintf(stderr, "\t0... is interpreted as octal,\n"); (void) fprintf(stderr, "\totherwise, decimal.\n"); /* Get the message queue ID and set up the message buffer. */ (void) fprintf(stderr, "Enter msqid: "); (void) scanf("%i", &msqid); /* * Note that <sys/msg.h> includes a definition of struct msgbuf * with the mtext field defined as: * char mtext[1]; * therefore, this definition is only a template, not a structure * definition that you can use directly, unless you want only to * send and receive messages of 0 or 1 byte. To handle this, * malloc an area big enough to contain the template - the size * of the mtext template field + the size of the mtext field * wanted. Then you can use the pointer returned by malloc as a

Page 85: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

* struct msgbuf with an mtext field of the size you want. Note * also that sizeof msgp->mtext is valid even though msgp isn't * pointing to anything yet. Sizeof doesn't dereference msgp, but * uses its type to figure out what you are asking about. */ (void) fprintf(stderr, "Enter the message buffer size you want:"); (void) scanf("%i", &maxmsgsz); if (maxmsgsz < 0) { (void) fprintf(stderr, "msgop: %s\n", "The message buffer size must be >= 0."); exit(1); } msgp = (struct msgbuf *)malloc((unsigned)(sizeof(struct msgbuf) - sizeof msgp->mtext + maxmsgsz)); if (msgp == NULL) { (void) fprintf(stderr, "msgop: %s %d byte messages.\n", "could not allocate message buffer for", maxmsgsz); exit(1); } /* Loop through message operations until the user is ready to quit. */ while (choice = ask()) { switch (choice) { case 1: /* msgsnd() requested: Get the arguments, make the call, and report the results. */ (void) fprintf(stderr, "Valid msgsnd message %s\n", "types are positive integers."); (void) fprintf(stderr, "Enter msgp->mtype: "); (void) scanf("%li", &msgp->mtype); if (maxmsgsz) { /* Since you've been using scanf, you need the loop below to throw away the rest of the input on the line after the entered mtype before you start reading the mtext. */ while ((c = getchar()) != '\n' && c != EOF); (void) fprintf(stderr, "Enter a %s:\n", "one line message"); for (i = 0; ((c = getchar()) != '\n'); i++) { if (i >= maxmsgsz) { (void) fprintf(stderr, "\n%s\n", full_buf); while ((c = getchar()) != '\n'); break;

Page 86: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

} msgp->mtext[i] = c; } msgsz = i; } else msgsz = 0; (void) fprintf(stderr,"\nMeaningful msgsnd flag is:\n"); (void) fprintf(stderr, "\tIPC_NOWAIT =\t%#8.8o\n", IPC_NOWAIT); (void) fprintf(stderr, "Enter msgflg: "); (void) scanf("%i", &msgflg); (void) fprintf(stderr, "%s(%d, msgp, %d, %#o)\n", "msgop: Calling msgsnd", msqid, msgsz, msgflg); (void) fprintf(stderr, "msgp->mtype = %ld\n", msgp->mtype); (void) fprintf(stderr, "msgp->mtext = \""); for (i = 0; i < msgsz; i++) (void) fputc(msgp->mtext[i], stderr); (void) fprintf(stderr, "\"\n"); rtrn = msgsnd(msqid, msgp, msgsz, msgflg); if (rtrn == -1) perror("msgop: msgsnd failed"); else (void) fprintf(stderr, "msgop: msgsnd returned %d\n", rtrn); break; case 2: /* msgrcv() requested: Get the arguments, make the call, and report the results. */ for (msgsz = -1; msgsz < 0 || msgsz > maxmsgsz; (void) scanf("%i", &msgsz)) (void) fprintf(stderr, "%s (0 <= msgsz <= %d): ", "Enter msgsz", maxmsgsz); (void) fprintf(stderr, "msgtyp meanings:\n"); (void) fprintf(stderr, "\t 0 %s\n", first_on_queue); (void) fprintf(stderr, "\t>0 %s of given type\n", first_on_queue); (void) fprintf(stderr, "\t<0 %s with type <= |msgtyp|\n", first_on_queue); (void) fprintf(stderr, "Enter msgtyp: "); (void) scanf("%li", &msgtyp); (void) fprintf(stderr, "Meaningful msgrcv flags are:\n"); (void) fprintf(stderr, "\tMSG_NOERROR =\t%#8.8o\n", MSG_NOERROR); (void) fprintf(stderr, "\tIPC_NOWAIT =\t%#8.8o\n", IPC_NOWAIT);

Page 87: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

(void) fprintf(stderr, "Enter msgflg: "); (void) scanf("%i", &msgflg); (void) fprintf(stderr, "%s(%d, msgp, %d, %ld, %#o);\n", "msgop: Calling msgrcv", msqid, msgsz, msgtyp, msgflg); rtrn = msgrcv(msqid, msgp, msgsz, msgtyp, msgflg); if (rtrn == -1) perror("msgop: msgrcv failed"); else { (void) fprintf(stderr, "msgop: %s %d\n", "msgrcv returned", rtrn); (void) fprintf(stderr, "msgp->mtype = %ld\n", msgp->mtype); (void) fprintf(stderr, "msgp->mtext is: \""); for (i = 0; i < rtrn; i++) (void) fputc(msgp->mtext[i], stderr); (void) fprintf(stderr, "\"\n"); } break; default: (void) fprintf(stderr, "msgop: operation unknown\n"); break; } } exit(0); } /* * Ask the user what to do next. Return the user's choice code. * Don't return until the user selects a valid choice. */ static ask() { int response; /* User's response. */ do { (void) fprintf(stderr, "Your options are:\n"); (void) fprintf(stderr, "\tExit =\t0 or Control-D\n"); (void) fprintf(stderr, "\tmsgsnd =\t1\n"); (void) fprintf(stderr, "\tmsgrcv =\t2\n"); (void) fprintf(stderr, "Enter your choice: "); /* Preset response so "^D" will be interpreted as exit. */ response = 0; (void) scanf("%i", &response);

Page 88: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

SRM Un

} while ( return(re} SEMAPH

Insight a

First let unothing bcomes inFor instaIn this evdone by a

The valuWhen thethe valuereinitializtwo procsame file

Where a

We have In this caread and For this rprocesses

Details of

The com

$ ipcs –s

will give

Function

The funcas input n

Name of called as

U

iversity

(response <

esponse);

HORE

about Semap

us begin our but a term usn mind is whance there mavent we mustassigning va

ue of the seme second proe as initializezes the semaesses but a s

e. Thus sema

Semaphore

seen that sease we must check the va

reason only ts.

of Semaphor

mand

the list of ex

n to create a

ction that cannamely:

f the semaphokey of the s

Unix and

Depa

0 || response

phore:

topic by givsed in UNIXat for we neay be times wt control the

alue to semap

maphore is inocess try to aed it does noaphore valuesemaphore caphores are u

e gets stored

emaphore canmake the sealue and alsothe semapho

re

xisting sema

a simple sem

n be used to

ore with whisemaphore.

d networ

artment of

e > 2);

ving an insigX for a variab

ed this variawhen two pr

e access of thphore.

itialized by taccess the filot access the e and now than be used e

used to coord

n be used whmaphore avao initialize aore is stored

aphores.

maphore

create semap

ich we are g

rk Progr

Computer A

ght to what isble which acable. It’s so srocesses try he file when

the first procle it checks tfile. After the second pro

even when ndinate acces

hen numbersailable acces

and reinitializin kernel s

phores is sem

going to crea

rammin

Application

s actually a scts as a countsimple. The rto access thethe other pr

cess when ththe value of he first proceocess uses it

numbers of ps to a resour

s of processessible to all pze the value so that it can

mget( ). This

ate the semap

ng MC06

s S

semaphore. Ater. So the nreason is expe same file socess is acce

he file is in athe semaphoess is compl. The above rocesses try

rce by differe

es try to acceprocesses soof semapho

n be accessed

s function ta

phore. This i

618  201

S.Kanchana

A semaphorext questionplained belo

simultaneousessing. This

access by it. ore and if it feted it example is fto access th

ent processe

ess the sameo that they caore appropriad by all

akes 3 argum

is technically

12 

Devi

re is n that ow. sly. is

finds

for he es

e file. an ately.

ments

y

Page 89: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The number of sub semaphores to be created. The minimum required number is 1.

The semaphore mode is specified. There are 2 modes in semaphore namely read and rewrite.

The return integer value from this function indicates the semaphore id with which the semaphore is associated and if the return integer is -1 it indicates that an error has occurred in the creation of semaphore.

How Kernel maintains internally the semaphores:

For every semaphore created a structure is created inside by the kernel byname semid_ds and this structure is found in header file sys/ipc.h.

How to set user defined values for semaphore:

In the create semaphore function we saw that the semaphore created returns a semaphore id which is system generated. By we could realize in real usage scenarios it would prove helpful only when the user would be able to define the value of the semaphore. This is because if the user would be able to define the value of the semaphore then they could design easily stating the numbers they have given for semaphores .For instance number one may be used to mark that semaphore is free and say number two to mark the semaphore is in use by another process and so on. This can be done by using the following functions and values namely:

semctl( ) GETPID SETVAL along with semget( ) which we used before for creating semaphores.

Let us see in brief how to do this:

• The first step is to create semaphore as we discussed before by using semget( ) function which returns the semaphore id.

• Before seeing how to do this first let us see what the semctl( ) function takes as arguments. It takes 4 parameters as arguments namely:

• The semaphore id created by semget( ) function • Sub semaphore id. For the first time it would be zero since it gets created that time. • GETPID. This returns the Process id of the process. • value to be placed for the above process id. This value only will be returned by the

function semctl( ). • After this by using SETVAL in semctl( ) function with all the arguments the same except

instead of GETPID we place SETVAL and give the value to be placed in this which is returned by the semctl( ) function.

This is how we assign user defined values to semaphores which give ease of maintenance and use of semaphores by users.

Page 90: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Aspects of Semaphore:

• Semaphores are identified by semaphore id which is unique for each semaphore. • The semaphores can be deleted by suing the function semdelete(semaphore) • The semaphore value can be incremented or decremented by using functions wait (sem)

and signal (sem) respectively. wait (sem) decrements the semaphore value and if in the process of decrementing the value of semaphore reaches negative value then the process is suspended and placed in queue for waiting. signal (sem) increments the value of the semaphore and it is opposite in action to wait (sem).In other words it causes the first process in queue to get executed.

The value of semaphore represents thus the number of threads which are nothing but processes. In other words we found that if the value is positive then we have threads to decrement and proceed for execution without suspending. If the value of semaphore is negative then it represents that the number of threads or process is blocked and kept in suspended state. If the value of semaphore is zero then it means that there are no threads or processes in waiting state. So from the above the important fact in semaphores is when we create semaphores we found that semaphores can be assigned with any value. Also we found from above that after creation of semaphores we can modify that is either increment or decrement the value of semaphores. But at any situation we cannot read the current value of semaphore.

IPC:Shared Memory

Shared Memory is an efficeint means of passing data between programs. One program will create a memory portion which other processes (if permitted) can access.

In the Solaris 2.x operating system, the most efficient way to implement shared memory applications is to rely on the mmap() function and on the system's native virtual memory facility. Solaris 2.x also supports System V shared memory, which is another way to let multiple processes attach a segment of physical memory to their virtual address spaces. When write access is allowed for more than one process, an outside protocol or mechanism such as a semaphore can be used to prevent inconsistencies and collisions.

A process creates a shared memory segment using shmget()|. The original owner of a shared memory segment can assign ownership to another user with shmctl(). It can also revoke this assignment. Other processes with proper permission can perform various control functions on the shared memory segment using shmctl(). Once created, a shared segment can be attached to a process address space using shmat(). It can be detached using shmdt() (see shmop()). The attaching process must have the appropriate permissions for shmat(). Once attached, the process can read or write to the segment, as allowed by the permission requested in the attach operation. A shared segment can be attached multiple times by the same process. A shared memory segment is described by a control structure with a unique ID that points to an area of physical memory. The identifier of the segment is called the shmid. The structure definition for the shared memory segment control structures and prototypews can be found in <sys/shm.h>.

Page 91: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Accessing a Shared Memory Segment

shmget() is used to obtain access to a shared memory segment. It is prottyped by:

int shmget(key_t key, size_t size, int shmflg);

The key argument is a access value associated with the semaphore ID. The size argument is the size in bytes of the requested shared memory. The shmflg argument specifies the initial access permissions and creation control flags.

When the call succeeds, it returns the shared memory segment ID. This call is also used to get the ID of an existing shared segment (from a process requesting sharing of some existing memory portion).

The following code illustrates shmget():

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> ... key_t key; /* key to be passed to shmget() */ int shmflg; /* shmflg to be passed to shmget() */ int shmid; /* return value from shmget() */ int size; /* size to be passed to shmget() */ ... key = ... size = ... shmflg) = ... if ((shmid = shmget (key, size, shmflg)) == -1) { perror("shmget: shmget failed"); exit(1); } else { (void) fprintf(stderr, "shmget: shmget returned %d\n", shmid); exit(0); } ... Controlling a Shared Memory Segment

shmctl() is used to alter the permissions and other characteristics of a shared memory segment. It is prototyped as follows:

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

Page 92: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The process must have an effective shmid of owner, creator or superuser to perform this command. The cmd argument is one of following control commands:

SHM_LOCK -- Lock the specified shared memory segment in memory. The process must have the effective ID of superuser to perform this command.

SHM_UNLOCK -- Unlock the shared memory segment. The process must have the effective ID of superuser to perform this command.

IPC_STAT -- Return the status information contained in the control structure and place it in the buffer pointed to by buf. The process must have read permission on the segment to perform this command.

IPC_SET -- Set the effective user and group identification and access permissions. The process must have an effective ID of owner, creator or superuser to perform this command.

IPC_RMID -- Remove the shared memory segment.

The buf is a sructure of type struct shmid_ds which is defined in <sys/shm.h>

The following code illustrates shmctl():

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> ... int cmd; /* command code for shmctl() */ int shmid; /* segment ID */ struct shmid_ds shmid_ds; /* shared memory data structure to hold results */ ... shmid = ... cmd = ... if ((rtrn = shmctl(shmid, cmd, shmid_ds)) == -1) { perror("shmctl: shmctl failed"); exit(1); } ... Attaching and Detaching a Shared Memory Segment

shmat() and shmdt() are used to attach and detach shared memory segments. They are prototypes as follows:

Page 93: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

void *shmat(int shmid, const void *shmaddr, int shmflg); int shmdt(const void *shmaddr);

shmat() returns a pointer, shmaddr, to the head of the shared segment associated with a valid shmid. shmdt() detaches the shared memory segment located at the address indicated by shmaddr

. The following code illustrates calls to shmat() and shmdt():

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> static struct state { /* Internal record of attached segments. */ int shmid; /* shmid of attached segment */ char *shmaddr; /* attach point */ int shmflg; /* flags used on attach */ } ap[MAXnap]; /* State of current attached segments. */ int nap; /* Number of currently attached segments. */ ... char *addr; /* address work variable */ register int i; /* work area */ register struct state *p; /* ptr to current state entry */ ... p = &ap[nap++]; p->shmid = ... p->shmaddr = ... p->shmflg = ... p->shmaddr = shmat(p->shmid, p->shmaddr, p->shmflg); if(p->shmaddr == (char *)-1) { perror("shmop: shmat failed"); nap--;

} else (void) fprintf(stderr, "shmop: shmat returned %#8.8x\n", p->shmaddr); ... i = shmdt(addr); if(i == -1) { perror("shmop: shmdt failed"); } else { (void) fprintf(stderr, "shmop: shmdt returned %d\n", i);

Page 94: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

for (p = ap, i = nap; i--; p++) if (p->shmaddr == addr) *p = ap[--nap]; } ... Example two processes comunicating via shared memory: shm_server.c, shm_client.c

We develop two programs here that illustrate the passing of a simple piece of memery (a string) between the processes if running simulatenously:

shm_server.c -- simply creates the string and shared memory portion.

shm_client.c -- attaches itself to the created shared memory portion and uses the string (printf.

The code listings of the 2 programs no follow:

shm_server.c #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #define SHMSZ 27 main() { char c; int shmid; key_t key; char *shm, *s; /* * We'll name our shared memory segment * "5678".

*/ key = 5678; /* * Create the segment. */ if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); }

Page 95: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

/* * Now we attach the segment to our data space. */ if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } /* * Now put some things into the memory for the * other process to read. */ s = shm; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = NULL; /* * Finally, we wait until the other process * changes the first character of our memory * to '*', indicating that it has read what * we put there. */ while (*shm != '*') sleep(1); exit(0); } shm_client.c /* * shm-client - client program to demonstrate shared memory. */ #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #define SHMSZ 27 main() { int shmid; key_t key; char *shm, *s;

Page 96: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

/* * We need to get the segment named * "5678", created by the server. */ key = 5678; /* * Locate the segment. */ if ((shmid = shmget(key, SHMSZ, 0666)) < 0) { perror("shmget"); exit(1); } /* * Now we attach the segment to our data space. */ if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } /* * Now read what the server put in the memory. */ for (s = shm; *s != NULL; s++) putchar(*s); putchar('\n'); /* * Finally, change the first character of the * segment to '*', indicating we have read * the segment. */ *shm = '*'; exit(0); }

POSIX Shared Memory

POSIX shared memory is actually a variation of mapped memory. The major differences are to use shm_open() to open the shared memory object (instead of calling open()) and use shm_unlink() to close and delete the object (instead of calling close() which does not remove the object). The options in shm_open() are substantially fewer than the number of options provided in open().

Page 97: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Mapped memory

In a system with fixed memory (non-virtual), the address space of a process occupies and is limited to a portion of the system's main memory. In Solaris 2.x virtual memory the actual address space of a process occupies a file in the swap partition of disk storage (the file is called the backing store). Pages of main memory buffer the active (or recently active) portions of the process address space to provide code for the CPU(s) to execute and data for the program to process.

A page of address space is loaded when an address that is not currently in memory is accessed by a CPU, causing a page fault. Since execution cannot continue until the page fault is resolved by reading the referenced address segment into memory, the process sleeps until the page has been read. The most obvious difference between the two memory systems for the application developer is that virtual memory lets applications occupy much larger address spaces. Less obvious advantages of virtual memory are much simpler and more efficient file I/O and very efficient sharing of memory between processes.

Address Spaces and Mapping

Since backing store files (the process address space) exist only in swap storage, they are not included in the UNIX named file space. (This makes backing store files inaccessible to other processes.) However, it is a simple extension to allow the logical insertion of all, or part, of one, or more, named files in the backing store and to treat the result as a single address space. This is called mapping. With mapping, any part of any readable or writable file can be logically included in a process's address space. Like any other portion of the process's address space, no page of the file is not actually loaded into memory until a page fault forces this action. Pages of memory are written to the file only if their contents have been modified. So, reading from and writing to files is completely automatic and very efficient. More than one process can map a single named file. This provides very efficient memory sharing between processes. All or part of other files can also be shared between processes.

Not all named file system objects can be mapped. Devices that cannot be treated as storage, such as terminal and network device files, are examples of objects that cannot be mapped. A process address space is defined by all of the files (or portions of files) mapped into the address space. Each mapping is sized and aligned to the page boundaries of the system on which the process is executing. There is no memory associated with processes themselves.

A process page maps to only one object at a time, although an object address may be the subject of many process mappings. The notion of a "page" is not a property of the mapped object. Mapping an object only provides the potential for a process to read or write the object's contents. Mapping makes the object's contents directly addressable by a process. Applications can access the storage resources they use directly rather than indirectly through read and write. Potential advantages include efficiency (elimination of unnecessary data copying) and reduced complexity (single-step updates rather than the read, modify buffer, write cycle). The ability to access an object and have it retain its identity over the course of the access is unique to this access method, and facilitates the sharing of common code and data.

Page 98: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Because the file system name space includes any directory trees that are connected from other systems via NFS, any networked file can also be mapped into a process's address space

shmget.c:Sample Program to Illustrate shmget() /* * shmget.c: Illustrate the shmget() function. * * This is a simple exerciser of the shmget() function. It prompts * for the arguments, makes the call, and reports the results. */ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> extern void exit(); extern void perror(); main() { key_t key; /* key to be passed to shmget() */ int shmflg; /* shmflg to be passed to shmget() */ int shmid; /* return value from shmget() */ int size; /* size to be passed to shmget() */ (void) fprintf(stderr, "All numeric input is expected to follow C conventions:\n"); (void) fprintf(stderr, "\t0x... is interpreted as hexadecimal,\n"); (void) fprintf(stderr, "\t0... is interpreted as octal,\n"); (void) fprintf(stderr, "\totherwise, decimal.\n"); /* Get the key. */ (void) fprintf(stderr, "IPC_PRIVATE == %#lx\n", IPC_PRIVATE); (void) fprintf(stderr, "Enter key: "); (void) scanf("%li", &key); /* Get the size of the segment. */ (void) fprintf(stderr, "Enter size: "); (void) scanf("%i", &size); /* Get the shmflg value. */ (void) fprintf(stderr, "Expected flags for the shmflg argument are:\n");

Page 99: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

(void) fprintf(stderr, "\tIPC_CREAT = \t%#8.8o\n", IPC_CREAT); (void) fprintf(stderr, "\tIPC_EXCL = \t%#8.8o\n", IPC_EXCL); (void) fprintf(stderr, "\towner read =\t%#8.8o\n", 0400); (void) fprintf(stderr, "\towner write =\t%#8.8o\n", 0200); (void) fprintf(stderr, "\tgroup read =\t%#8.8o\n", 040); (void) fprintf(stderr, "\tgroup write =\t%#8.8o\n", 020); (void) fprintf(stderr, "\tother read =\t%#8.8o\n", 04); (void) fprintf(stderr, "\tother write =\t%#8.8o\n", 02); (void) fprintf(stderr, "Enter shmflg: "); (void) scanf("%i", &shmflg); /* Make the call and report the results. */ (void) fprintf(stderr, "shmget: Calling shmget(%#lx, %d, %#o)\n", key, size, shmflg); if ((shmid = shmget (key, size, shmflg)) == -1) { perror("shmget: shmget failed"); exit(1); } else { (void) fprintf(stderr, "shmget: shmget returned %d\n", shmid); exit(0); } }

Although Unix sockets are a special file in the file system (just like FIFOs), you won't be using open() and read()—you'll be using socket(), bind(), recv(), etc.

When programming with sockets, you'll usually create server and client programs. The server will sit listening for incoming connections from clients and handle them. This is very similar to the situation that exists with Internet sockets, but with some fine differences.

For instance, when describing which Unix socket you want to use (that is, the path to the special file that is the socket), you use a struct sockaddr_un, which has the following fields:

struct sockaddr_un { unsigned short sun_family; /* AF_UNIX */ char sun_path[108]; }

This is the structure you will be passing to the bind() function, which associates a socket descriptor (a file descriptor) with a certain file (the name for which is in the sun_path field).

11.2. What to do to be a Server

Page 100: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Without going into too much detail, I'll outline the steps a server program usually has to go through to do it's thing. While I'm at it, I'll be trying to implement an "echo server" which just echos back everything it gets on the socket.

Here are the server steps:

1. Call socket(): A call to socket() with the proper arguments creates the Unix socket:

2. unsigned int s, s2; 3. struct sockaddr_un local, remote; 4. int len; 5.

s = socket(AF_UNIX, SOCK_STREAM, 0);

The second argument, SOCK_STREAM, tells socket() to create a stream socket. Yes, datagram sockets (SOCK_DGRAM) are supported in the Unix domain, but I'm only going to cover stream sockets here. For the curious, see Beej's Guide to Network Programming for a good description of unconnected datagram sockets that applies perfectly well to Unix sockets. The only thing that changes is that you're now using a struct sockaddr_un instead of a struct sockaddr_in.

One more note: all these calls return -1 on error and set the global variable errno to reflect whatever went wrong. Be sure to do your error checking.

6. Call bind(): You got a socket descriptor from the call to socket(), now you want to bind that to an address in the Unix domain. (That address, as I said before, is a special file on disk.)

7. local.sun_family = AF_UNIX; /* local is declared before socket() ^ */ 8. strcpy(local.sun_path, "/home/beej/mysocket"); 9. unlink(local.sun_path); 10. len = strlen(local.sun_path) + sizeof(local.sun_family);

bind(s, (struct sockaddr *)&local, len);

This associates the socket descriptor "s" with the Unix socket address "/home/beej/mysocket". Notice that we called unlink() before bind() to remove the socket if it already exists. You will get an EINVAL error if the file is already there.

11. Call listen(): This instructs the socket to listen for incoming connections from client programs:

listen(s, 5);

Page 101: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The second argument, 5, is the number of incoming connections that can be queued before you call accept(), below. If there are this many connections waiting to be accepted, additional clients will generate the error ECONNREFUSED.

12. Call accept(): This will accept a connection from a client. This function returns another socket descriptor! The old descriptor is still listening for new connections, but this new one is connected to the client:

13. len = sizeof(struct sockaddr_un);

s2 = accept(s, &remote, &len);

When accept() returns, the remote variable will be filled with the remote side's struct sockaddr_un, and len will be set to its length. The descriptor s2 is connected to the client, and is ready for send() and recv(), as described in the Network Programming Guide.

14. Handle the connection and loop back to accept(): Usually you'll want to communicate to the client here (we'll just echo back everything it sends us), close the connection, then accept() a new one.

15. while (len = recv(s2, &buf, 100, 0), len > 0) 16. send(s2, &buf, len, 0); 17.

/* loop back to accept() from here */

18. Close the connection: You can close the connection either by calling close(), or by calling shutdown().

With all that said, here is some source for an echoing server, echos.c. All it does is wait for a connection on a Unix socket (named, in this case, "echo_socket").

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #define SOCK_PATH "echo_socket" int main(void) {

Page 102: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

int s, s2, t, len; struct sockaddr_un local, remote; char str[100]; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } local.sun_family = AF_UNIX; strcpy(local.sun_path, SOCK_PATH); unlink(local.sun_path); len = strlen(local.sun_path) + sizeof(local.sun_family); if (bind(s, (struct sockaddr *)&local, len) == -1) { perror("bind"); exit(1); } if (listen(s, 5) == -1) { perror("listen"); exit(1); } for(;;) { int done, n; printf("Waiting for a connection...\n"); t = sizeof(remote); if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) { perror("accept"); exit(1); } printf("Connected.\n"); done = 0; do { n = recv(s2, str, 100, 0); if (n <= 0) { if (n < 0) perror("recv");

Page 103: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

done = 1; } if (!done) if (send(s2, str, n, 0) < 0) { perror("send"); done = 1; } } while (!done); close(s2); } return 0; }

As you can see, all the aforementioned steps are included in this program: call socket(), call bind(), call listen(), call accept(), and do some network send()s and recv()s.

11.3. What to do to be a client

There needs to be a program to talk to the above server, right? Except with the client, it's a lot easier because you don't have to do any pesky listen()ing or accept()ing. Here are the steps:

1. Call socket() to get a Unix domain socket to communicate through. 2. Set up a struct sockaddr_un with the remote address (where the server is listening)

and call connect() with that as an argument 3. Assuming no errors, you're connected to the remote side! Use send() and recv() to

your heart's content!

How about code to talk to the echo server, above? No sweat, friends, here is echoc.c:

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #define SOCK_PATH "echo_socket"

Page 104: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

int main(void) { int s, t, len; struct sockaddr_un remote; char str[100]; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } printf("Trying to connect...\n"); remote.sun_family = AF_UNIX; strcpy(remote.sun_path, SOCK_PATH); len = strlen(remote.sun_path) + sizeof(remote.sun_family); if (connect(s, (struct sockaddr *)&remote, len) == -1) { perror("connect"); exit(1); } printf("Connected.\n"); while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) { if (send(s, str, strlen(str), 0) == -1) { perror("send"); exit(1); } if ((t=recv(s, str, 100, 0)) > 0) { str[t] = '\0'; printf("echo> %s", str); } else { if (t < 0) perror("recv"); else printf("Server closed connection\n"); exit(1); } }

Page 105: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

close(s); return 0; }

In the client code, of course you'll notice that there are only a few system calls used to set things up: socket() and connect(). Since the client isn't going to be accept()ing any incoming connections, there's no need for it to listen(). Of course, the client still uses send() and recv() for transferring data. That about sums it up.

11.4. socketpair()—quick full-duplex pipes

What if you wanted a pipe(), but you wanted to use a single pipe to send and recieve data from both sides? Since pipes are unidirectional (with exceptions in SYSV), you can't do it! There is a solution, though: use a Unix domain socket, since they can handle bi-directional data.

What a pain, though! Setting up all that code with listen() and connect() and all that just to pass data both ways! But guess what! You don't have to!

That's right, there's a beauty of a system call known as socketpair() this is nice enough to return to you a pair of already connected sockets! No extra work is needed on your part; you can immediately use these socket descriptors for interprocess communication.

For instance, lets set up two processes. The first sends a char to the second, and the second changes the character to uppercase and returns it. Here is some simple code to do just that, called spair.c (with no error checking for clarity):

#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> int main(void) { int sv[2]; /* the pair of socket descriptors */ char buf; /* for data exchange between processes */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {

Page 106: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

perror("socketpair"); exit(1); } if (!fork()) { /* child */ read(sv[1], &buf, 1); printf("child: read '%c'\n", buf); buf = toupper(buf); /* make it uppercase */ write(sv[1], &buf, 1); printf("child: sent '%c'\n", buf); } else { /* parent */ write(sv[0], "b", 1); printf("parent: sent 'b'\n"); read(sv[0], &buf, 1); printf("parent: read '%c'\n", buf); wait(NULL); /* wait for child to die */ } return 0; }

Sure, it's an expensive way to change a character to uppercase, but it's the fact that you have simple communication going on here that really matters.

One more thing to notice is that socketpair() takes both a domain (AF_UNIX) and socket type (SOCK_STREAM). These can be any legal values at all, depending on which routines in the kernel you want to handle your code, and whether you want stream or datagram sockets. I chose AF_UNIX sockets because this is a Unix sockets document and they're a bit faster than AF_INET sockets, I hear.

Finally, you might be curious as to why I'm using write() and read() instead of send() and recv(). Well, in short, I was being lazy. See, by using these system calls, I don't have to enter the flags argument that send() and recv() use, and I always set it to zero anyway. Of course, socket descriptors are just file descriptors like any other, so they respond just fine to many file manipulation system calls.

TCP SOCKETS

Programming with TCP/IP sockets

There are a few steps involved in using sockets:

Page 107: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

1. Create the socket

2. Identify the socket

3. On the server, wait for an incoming connection

4. On the client, connect to the server's socket

5. Send and receive messages

6. Close the socket

Step 1. Create a socket A socket, s, is created with the socket system call:

int s = socket(domain, type, protocol) All the parameters as well as the return value are integers:

domain, or address family —

communication domain in which the socket should be created. Some of address

families are AF_INET (IP), AF_INET6 (IPv6), AF_UNIX (local channel, similar to

pipes), AF_ISO (ISO protocols), and AF_NS (Xerox Network Systems protocols).

type —

type of service. This is selected according to the properties required by the

application: SOCK_STREAM (virtual circuit service), SOCK_DGRAM (datagram

service), SOCK_RAW (direct IP service). Check with your address family to see

whether a particular service is available.

protocol —

indicate a specific protocol to use in supporting the sockets operation. This is useful

in cases where some families may have more than one protocol to support a given

type of service. The return value is a file descriptor (a small integer). The analogy of

creating a socket is that of requesting a telephone line from the phone company.

Page 108: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

For TCP/IP sockets, we want to specify the IP address family (AF_INET) and virtual

circuit service (SOCK_STREAM). Since there's only one form of virtual circuit

service, there are no variations of the protocol, so the last argument, protocol, is zero.

Our code for creating a TCP socket looks like this

#include <sys/socket.h>

...

if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {

perror("cannot create socket");

return 0;

}

Step 2. Indentify (name) a socket When we talk about naming a socket, we are talking about assigning a transport address to the

socket (a port number in IP networking). In sockets, this operation is called binding an address

and the bind system call is used for this. The analogy is that of assigning a phone number to the

line that you requested from the phone company in step 1 or that of assigning an address to a

mailbox.

The transport address is defined in a socket address structure. Because sockets were designed to

work with various different types of communication interfaces, the interface is very general.

Instead of accepting, say, a port number as a parameter, it takes a sockaddr structure whose

actual format is determined on the address family (type of network) you're using. For example, if

you're using UNIX domain sockets, bind actually creates a file in the file system.

The system call for bind is:

Page 109: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

#include <sys/socket.h> int bind(int socket, const struct sockaddr *address, socklen_t address_len); The first parameter, socket, is the socket that was created with the socket system call.

For the second parameter, the structure sockaddr is a generic container that just allows the OS to

be able to read the first couple of bytes that identify the address family. The address family

determines what variant of the sockaddr struct to use that contains elements that make sense for

that specific communication type. For IP networking, we use struct sockaddr_in, which is

defined in the header netinet/in.h. This structure defines:

struct sockaddr_in { __uint8_t sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; char sin_zero[8]; }; Before calling bind, we need to fill out this structure. The three key parts we need to set are:

sin_family

The address family we used when we set up the socket. In our case, it's AF_INET.

sin_port

The port number (the transport address). You can explicitly assign a transport address

(port) or allow the operating system to assign one. If you're a client and won't be

receiving incoming connections, you'll usually just let the operating system pick any

available port number by specifying port 0. If you're a server, you'll generally pick a

specific number since clients will need to know a port number to connect to.

sin_addr

Page 110: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The address for this socket. This is just your machine's IP address. With IP, your

machine will have one IP address for each network interface. For example, if your

machine has both Wi-Fi and ethernet connections, that machine will have two

addresses, one for each interface. Most of the time, we don't care to specify a specific

interface and can let the operating system use whatever it wants. The special address

for this is 0.0.0.0, defined by the symbolic constant INADDR_ANY.

Since the address structure may differ based on the type of transport used, the third

parameter specifies the length of that structure. This is simply sizeof(struct

sockaddr_in).

The code to bind a socket looks like this:

#include <sys/socket.h>

...

struct sockaddr_in myaddr;

/* bind to an arbitrary return address */

/* because this is the client side, we don't care about the address */

/* since no application will connect here: */

/* INADDR_ANY is the IP address and 0 is the socket */

/* htonl converts a long integer (e.g. address) to a network representation */

/* htons converts a short integer (e.g. port) to a network representation */

memset((char *)&myaddr, 0, sizeof(myaddr));

myaddr.sin_family = AF_INET;

myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

myaddr.sin_port = htons(0);

Page 111: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {

perror("bind failed");

return 0;

}

Download a demo file Note: number conversions (htonl, htons, ntohl, ntohs) You might have noticed the htonl and htons references in the previous code block.

These convert four-byte and two-byte numbers into network representations. Integers

are stored in memory and sent across the network as sequences of bytes. There are

two common ways of storing these bytes: big endian and little endian notation. Little

endian representation stores the least-significant bytes in low memory. Big endian

representation stores the least-significant bytes in high memory. The Intel x86 family

uses the little endian format. Old Motorola processors and the PowerPC (used by

Macs before their switch to the Intel architecture) use the big endian format.

Internet headers standardized on using the big endian format. If you're on an Intel

processor and set the value of a port to 1,234 (hex equivalent 04d2), it will be be

stored in memory as d204. If it's stored in this order in a TCP/IP header, however, d2

will be treated as the most significant byte and the network protocols would read this

value as 53,764.

To keep code portable – and to keep you from having to write code to swap bytes and

worry about this &ndash a few convenience macros have been defined:

htons

host to network short : convert a number into a 16-bit network representation. This is

commonly used to store a port number into a sockaddr structure.

htonl

Page 112: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

host to network long : convert a number into a 32-bit network representation. This is

commonly used to store an IP address into a sockaddr structure.

ntohs

network to host short : convert a 16-bit number from a network representation into

the local processor's format. This is commonly used to read a port number from a

sockaddr structure.

ntohl

network to host long : convert a 32-bit number from a network representation into the

local processor's format. This is commonly used to read an IP address from a

sockaddr structure.

For processors that use the big endian format, these macros do absolutely

nothing. For those that use the little endian format (most processors, these

days), the macros flip the sequence of either four or two bytes. In the above

code, writing htonl(INADDR_ANY) and htons(0) is somewhat pointless

since all the bytes are zero anyway but it's good practice to remember to do

this at all times when reading or writing network data.

Step 3a. Connect to a server from a client If we're a client process, we need to establish a connection to the server.

Now that we have a socket that knows where it's coming from, we need to

tell it where it's going to. The connect system call accomplishes this.

#include <sys/types.h> #include <sys/socket.h> int connect(int socket, const struct sockaddr *address, socklen_t address_len);

Page 113: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The first parameter, socket, is the socket that was created with the socket

system call and named via bind. The second parameter identifies the

remotetransport address using the same sockaddr_in structure that we used

in bind to identify our local address. As with bind, the third parameter is

simply the length of the structure in the second parameter: sizeof(struct

sockaddr_in).

The server's address will contain the IP address of the server machine as

well as the port number that corresponds to a socket listening on that port

on that machine. The IP address is a four-byte (32 bit) value in network

byte order (see htonl above).

In most cases, you'll know the name of the machine but not its IP address.

An easy way of getting the IP address is with the gethostbyname library

(libc) function. Gethostbyname accepts a host name as a parameter and

returns a hostent structure:

struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses from name server */ };

If all goes well, the h_addr_list will contain a list of IP addresses. There

may be more than one IP addresses for a host. In practice, you should be

able to use any of the addresses or you may want to pick one that matches a

particular subnet. You may want to check that (h_addrtype == AF_INET)

and (h_length == 4) to ensure that you have a 32-bit IPv4 address. We'll be

lazy here and just use the first address in the list.

Page 114: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

For example, suppose you want to find the addresses for google.com. The

code will look like this:

#include <stdlib.h>

#include <stdio.h>

#include <netdb.h>

/* paddr: print the IP address in a standard decimal dotted format */

void

paddr(unsigned char *a)

{

printf("%d.%d.%d.%d\n", a[0], a[1], a[2], a[3]);

}

main(int argc, char **argv) {

struct hostent *hp;

char *host = "google.com";

int i;

hp = gethostbyname(host);

if (!hp) {

fprintf(stderr, "could not obtain address of %s\n", host);

return 0;

}

for (i=0; hp->h_addr_list[i] != 0; i++)

paddr((unsigned char*) hp->h_addr_list[i]);

exit(0);

}

Page 115: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Here's the code for establishing a connection to the address of a machine in

host. The variable fd is the socket which was created with the socket system

call.

#include <sys/types.h>

#include <sys/socket.h>

#include <stdio.h> /* for fprintf */

#include <string.h> /* for memcpy */

struct hostent *hp; /* host information */

struct sockaddr_in servaddr; /* server address */

/* fill in the server's address and data */

memset((char*)&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_port = htons(port);

/* look up the address of the server given its name */

hp = gethostbyname(host);

if (!hp) {

fprintf(stderr, "could not obtain address of %s\n", host);

return 0;

}

/* put the host's address into the server address structure */

memcpy((void *)&servaddr.sin_addr, hp->h_addr_list[0], hp-

>h_length);

/* connect to server */

Page 116: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

if (connect(fd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {

perror("connect failed");

return 0;

}

Step 3b. Accept connections on the server Before a client can connect to a server, the server should have a socket that

is prepared to accept the connections. The listen system call tells a socket

that it should be capable of accepting incoming connections:

#include <sys/socket.h> int listen(int socket, int backlog);

The second parameter, backlog, defines the maximum number of pending

connections that can be queued up before connections are refused.

The accept system call grabs the first connection request on the queue of

pending connections (set up in listen) and creates a new socket for that

connection. The original socket that was set up for listening is used only for

accepting connections, not for exchanging data. By default, socket

operations are synchronous, or blocking, and accept will block until a

connection is present on the queue. The syntax of accept is:

#include <sys/socket.h> int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len);

The first parameter, socket, is the socket that was set for accepting

connections with listen. The second parameter, address, is the address

Page 117: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

structure that gets filed in with the address of the client that is doing the

connect. This allows us to examine the address and port number of the

connecting socket if we want to. The third parameter is filled in with the

length of the address structure.

Let's examine a simple server. We'll create a socket, bind it to any available

IP address on the machine but to a specific port number. Then we'll set the

socket up for listening and loop, accepting connections.

#include <sys/types.h>

...

{

int port = 1234; /* port number */

int rqst; /* socket accepting the request */

socklen_t alen; /* length of address structure */

struct sockaddr_in my_addr; /* address of this service */

struct sockaddr_in client_addr; /* client's address */

int sockoptval = 1;

/* create a TCP/IP socket */

if ((svc = socket(AF_INET, SOCK_STREAM, 0)) < 0) {

perror("cannot create socket");

exit(1);

}

/* allow immediate reuse of the port */

Page 118: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

setsockopt(svc, SOL_SOCKET, SO_REUSEADDR,

&sockoptval, sizeof(int));

/* bind the socket to our source address */

memset((char*)&my_addr, 0, sizeof(my_addr)); /* 0 out the

structure */

my_addr.sin_family = AF_INET; /* address family */

my_addr.sin_port = htons(port);

my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

if (bind(svc, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)

{

perror("bind failed");

exit(1);

}

/* set the socket for listening (queue backlog of 5) */

if (listen(svc, 5) < 0) {

perror("listen failed");

exit(1);

}

/* loop, accepting connection requests */

for (;;) {

while ((rqst = accept(svc, (struct sockaddr *)&client_addr,

&alen)) < 0) {

/* we may break out of accept if the system call

*/

/* was interrupted. In this case, loop back and */

/* try again */

Page 119: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

if ((errno != ECHILD) && (errno != ERESTART)

&& (errno != EINTR)) {

perror("accept failed");

exit(1);

}

}

/* the socket for this accepted connection is rqst */

...

}

}

Download a demo file This code contains two special operations, marked in bold:

1. setsockopt(svc, SOL_SOCKET, SO_REUSEADDR, &sockoptval,

sizeof(int))

The setsockopt system call allows us to set special options on a socket. In this case,

we use setsockopt to set SO_REUSEADDR. This allows us to reuse the port

immediately as soon as the service exits. Some operating systems will not allow

immediate reuse on the chance that some packets may still be en route to the port.

Allowing us to reuse the port immediately is a huge help when debugging requires us

to start and restart the server over and over again.

2. if ((errno != ECHILD) && (errno != ERESTART) && (errno !=

EINTR))

accept is a blocking system call that returns when an incoming connection has been

received. However, on some operating systems it may return if other signals have

been received, such as a death of a child process (ECHILD), an interrupted system

call that should be restarted (ERESTART), or just an interrupted system call

(EINTR). If any of these signals have been received then we loop back and continue

waiting for a connection. Otherwise we print an error message and exit.

Page 120: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Step 4. Communicate We finally have connected sockets between a client and a server!

Communication is the easy part. The same read and write system calls

that work on files also work on sockets. We can send 20 bytes from

the client to server with:

char buffer[MAXBUF]; ... nbytes = write(fd, buffer, 20); /* write 20 bytes in buffer */

We can read a bunch of data from the client with:

char buffer[MAXBUF]; ... nbytes = read(fd, buffer, MAXBUF); /* read up to MAXBUF bytes */

One important thing to keep in mind is that TCP/IP sockets give you a

byte stream, not a packet stream. If you write 20 bytes to a socket, the

other side is not guaranteed to read 20 bytes in a read operation. It

may read 20. It may read less if there was some packet fragmentation.

In that case, you'll need to loop back and keep reading. If you write 20

bytes to a socket and then write another 20 bytes to a socket, the other

side may read all 40 bytes at once ... or not.

If the amount of data you want to read matters then it's up to you to

create a protocol that lets you know what to read, such as sending a

length count prior to sending data.

A few additional system calls were added. We can ignore them most

of the time but should know they exist for the times we may need

them. All of these functions support an extra flags parameter. The

Page 121: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

actual capabilities may differ among different operating systems, so

check the documentation on a specific system. Some features that are

supported are quality of service control, out-of-band data transmission,

the ability to peek before reading incoming data abd and the ability to

bypass routing (mostly for debugging).

The send and recv calls are similar to read and write with the addition

of the flags parameter.

The sendto and recvfrom system calls are like send and recv but also

allow callers to specify or receive addresses of the peer with whom

they are communicating. This is most useful for connectionless

sockets.

Finally, sendmsg and recvmsg let one use a msghdr structure to

minimize the number of directly supplied arguments and also

minimize the numner of system calls by using scatter/gather to

read/write from/to a number of distinct memory blocks.

Could this have been designed cleaner and simpler? Probably. The

read/write or send/recv calls are designed be used primarily for

connection-oriented communication while sendto/recvfrom or

sendmsg/recvmsg are normally used for connectionless

communication since they allow one to specify the address.

Step 5. Close the connection When we're done communicating, the easiest thing to do is to close a

socket with the close system call — the same close that is used for

files.

Page 122: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

There's another way to close connections: the shutdonw system call.

#include <sys/socket.h> int shutdown(int socket, int how);

The second parameter, how, allows us to tell the socket what part of

the full-duplex connection to shut down:

A value of SHUT_RD will disallow further receives on that socket.

A value of SHUT_WR will disallow further sends on that socket.

A value of SHUT_RDWR will disallow both further sends and

receives on that socket.

Closing a socket with close(s) is identical to using shutdown(s, SHUT_RDWR).

Synchronous or Asynchronous? Network communication (or file system access in general) system calls may operate in two

modes: synchronous or asynchronous. In the synchronous mode, socket routines return only

when the operation is complete. For example, accept returns only when a connection arrives. In

the asynchronous mode, socket routines return immediately: system calls become non-blocking

calls (e.g., read does not block, waiting until data arrives). You can change the mode with the

fcntl system call. For example,

fcntl(s, F_SETFF, FNDELAY); sets the socket s to operate in asynchronous mode.

Page 123: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

<Sys.socket.h>

NAME sys/socket.h - main sockets header

SYNOPSIS

#include <sys/socket.h>

DESCRIPTION

The <sys/socket.h> header shall define the type socklen_t, which is an integer type of width of at least 32 bits; see APPLICATION USAGE.

The <sys/socket.h> header shall define the unsigned integer type sa_family_t.

The <sys/socket.h> header shall define the sockaddr structure that includes at least the following members:

sa_family_t sa_family Address family. char sa_data[] Socket address (variable-length data).

The sockaddr structure is used to define a socket address which is used in the bind(), connect(), getpeername(), getsockname(), recvfrom(), and sendto() functions.

The <sys/socket.h> header shall define the sockaddr_storage structure. This structure shall be:

• Large enough to accommodate all supported protocol-specific address structures • Aligned at an appropriate boundary so that pointers to it can be cast as pointers to

protocol-specific address structures and used to access the fields of those structures without alignment problems

The sockaddr_storage structure shall contain at least the following members:

sa_family_t ss_family

When a sockaddr_storage structure is cast as a sockaddr structure, the ss_family field of the sockaddr_storage structure shall map onto the sa_family field of the sockaddr structure. When a sockaddr_storage structure is cast as a protocol-specific address structure, the ss_family field shall map onto a field of that structure that is of type sa_family_t and that identifies the protocol's address family.

Page 124: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

The <sys/socket.h> header shall define the msghdr structure that includes at least the following members:

void *msg_name Optional address. socklen_t msg_namelen Size of address. struct iovec *msg_iov Scatter/gather array. int msg_iovlen Members in msg_iov. void *msg_control Ancillary data; see below. socklen_t msg_controllen Ancillary data buffer len. int msg_flags Flags on received message.

The msghdr structure is used to minimize the number of directly supplied parameters to the recvmsg() and sendmsg() functions. This structure is used as a value- result parameter in the recvmsg() function and value only for the sendmsg() function.

The iovec structure shall be defined as described in <sys/uio.h> .

The <sys/socket.h> header shall define the cmsghdr structure that includes at least the following members:

socklen_t cmsg_len Data byte count, including the cmsghdr. int cmsg_level Originating protocol. int cmsg_type Protocol-specific type.

BIND

NAME bind - bind a name to a socket

SYNOPSIS

#include <sys/socket.h> int bind(intsocket, const struct sockaddr *address, socklen_taddress_len);

Page 125: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

DESCRIPTION

The bind() function shall assign a local socket address address to a socket identified by descriptor socket that has no local socket address assigned. Sockets created with the socket() function are initially unnamed; they are identified only by their address family.

The bind() function takes the following arguments:

socket Specifies the file descriptor of the socket to be bound.

address Points to a sockaddr structure containing the address to be bound to the socket. The length and format of the address depend on the address family of the socket.

address_len Specifies the length of the sockaddr structure pointed to by the address argument.

The socket specified by socket may require the process to have appropriate privileges to use the bind() function.

RETURN VALUE

Upon successful completion, bind() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The bind() function shall fail if:

[EADDRINUSE] The specified address is already in use.

[EADDRNOTAVAIL] The specified address is not available from the local machine.

[EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket.

[EBADF] The socket argument is not a valid file descriptor.

[EINVAL] The socket is already bound to an address, and the protocol does not support binding to a new address; or the socket has been shut down.

[ENOTSOCK] The socket argument does not refer to a socket.

[EOPNOTSUPP] The socket type of the specified socket does not support binding to an address.

If the address family of the socket is AF_UNIX, then bind() shall fail if:

Page 126: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

[EACCES] A component of the path prefix denies search permission, or the requested name requires writing in a directory with a mode that denies write permission.

[EDESTADDRREQ] or [EISDIR] The address argument is a null pointer.

[EIO] An I/O error occurred.

[ELOOP] A loop exists in symbolic links encountered during resolution of the pathname in address.

[ENAMETOOLONG] A component of a pathname exceeded {NAME_MAX} characters, or an entire pathname exceeded {PATH_MAX} characters.

[ENOENT] A component of the pathname does not name an existing file or the pathname is an empty string.

[ENOTDIR] A component of the path prefix of the pathname in address is not a directory.

[EROFS] The name would reside on a read-only file system.

The bind() function may fail if:

[EACCES] The specified address is protected and the current user does not have permission to bind to it.

[EINVAL] The address_len argument is not a valid length for the address family.

[EISCONN] The socket is already connected.

[ELOOP] More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the pathname in address.

[ENAMETOOLONG] Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

[ENOBUFS] Insufficient resources were available to complete the call.

SOCKET

NAME socket - create an endpoint for communication

Page 127: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

SYNOPSIS

#include <sys/socket.h> int socket(intdomain, inttype, intprotocol);

DESCRIPTION

The socket() function shall create an unbound socket in a communications domain, and return a file descriptor that can be used in later function calls that operate on sockets.

The socket() function takes the following arguments:

domain Specifies the communications domain in which a socket is to be created.

type Specifies the type of socket to be created.

protocol Specifies a particular protocol to be used with the socket. Specifying a protocol of 0 causes socket() to use an unspecified default protocol appropriate for the requested socket type.

The domain argument specifies the address family used in the communications domain. The address families supported by the system are implementation-defined.

Symbolic constants that can be used for the domain argument are defined in the <sys/socket.h> header.

The type argument specifies the socket type, which determines the semantics of communication over the socket. The following socket types are defined; implementations may specify additional socket types:

SOCK_STREAM Provides sequenced, reliable, bidirectional, connection-mode byte streams, and may provide a transmission mechanism for out-of-band data.

SOCK_DGRAM Provides datagrams, which are connectionless-mode, unreliable messages of fixed maximum length.

SOCK_SEQPACKET Provides sequenced, reliable, bidirectional, connection-mode transmission paths for records. A record can be sent using one or more output operations and received using one or more input operations, but a single operation never transfers part of more than one record. Record boundaries are visible to the receiver via the MSG_EOR flag.

Page 128: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

If the protocol argument is non-zero, it shall specify a protocol that is supported by the address family. If the protocol argument is zero, the default protocol for this address family and type shall be used. The protocols supported by the system are implementation-defined.

The process may need to have appropriate privileges to use the socket() function or to create some sockets.

RETURN VALUE

Upon successful completion, socket() shall return a non-negative integer, the socket file descriptor. Otherwise, a value of -1 shall be returned and errno set to indicate the error.

CONNECT

NAME connect - connect a socket

SYNOPSIS

#include <sys/socket.h> int connect(intsocket, const struct sockaddr *address, socklen_taddress_len);

DESCRIPTION

The connect() function shall attempt to make a connection on a socket. The function takes the following arguments:

socket Specifies the file descriptor associated with the socket.

address Points to a sockaddr structure containing the peer address. The length and format of the address depend on the address family of the socket.

address_len Specifies the length of the sockaddr structure pointed to by the address argument.

If the socket has not already been bound to a local address, connect() shall bind it to an address which, unless the socket's address family is AF_UNIX, is an unused local address.

If the initiating socket is not connection-mode, then connect() shall set the socket's peer address, and no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all datagrams are sent on subsequent send() functions, and limits the remote sender for subsequent recv() functions. If address is a null address for the protocol, the socket's peer address shall be reset.

Page 129: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

If the initiating socket is connection-mode, then connect() shall attempt to establish a connection to the address specified by the address argument. If the connection cannot be established immediately and O_NONBLOCK is not set for the file descriptor for the socket, connect() shall block for up to an unspecified timeout interval until the connection is established. If the timeout interval expires before the connection is established, connect() shall fail and the connection attempt shall be aborted. If connect() is interrupted by a signal that is caught while blocked waiting to establish a connection, connect() shall fail and set errno to [EINTR], but the connection request shall not be aborted, and the connection shall be established asynchronously.

If the connection cannot be established immediately and O_NONBLOCK is set for the file descriptor for the socket, connect() shall fail and set errno to [EINPROGRESS], but the connection request shall not be aborted, and the connection shall be established asynchronously. Subsequent calls to connect() for the same socket, before the connection is established, shall fail and set errno to [EALREADY].

When the connection has been established asynchronously, select() and poll() shall indicate that the file descriptor for the socket is ready for writing.

The socket in use may require the process to have appropriate privileges to use the connect() function.

RETURN VALUE

Upon successful completion, connect() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error

SEND()

NAME send - send a message on a socket

SYNOPSIS

#include <sys/socket.h> ssize_t send(intsocket, const void *buffer, size_tlength, intflags);

DESCRIPTION

The send() function shall initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected (including when the peer of a connectionless socket has been set via connect()).

The send() function takes the following arguments:

Page 130: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

socket Specifies the socket file descriptor.

buffer Points to the buffer containing the message to send.

length Specifies the length of the message in bytes.

flags Specifies the type of message transmission. Values of this argument are formed by logically OR'ing zero or more of the following flags: MSG_EOR Terminates a record (if supported by the protocol). MSG_OOB Sends out-of-band data on sockets that support out-of-band communications. The significance and semantics of out-of-band data are protocol-specific.

The length of the message to be sent is specified by the length argument. If the message is too long to pass through the underlying protocol, send() shall fail and no data shall be transmitted.

Successful completion of a call to send() does not guarantee delivery of the message. A return value of -1 indicates only locally-detected errors.

If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does not have O_NONBLOCK set, send() shall block until space is available. If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does have O_NONBLOCK set, send() shall fail. The select()functions can be used to determine when it is possible to send more data.

The socket in use may require the process to have appropriate privileges to use the send() function.

RETURN VALUE

Upon successful completion, send() shall return the number of bytes sent. Otherwise, -1 shall be returned and errno set to indicate the error.

UDP sockets

SETL provides support for UDP (the User Datagram Protocol). Although this is an ``unreliable'' protocol in that it does not include software mechanisms for retrying on transmission failures or data corruption (unlike TCP), and has restrictions on message length (a little under 65536 bytes), it is needed for applications that use broadcasting or multicasting, and it underlies such important applications as NFS (the Network File System), DNS (the Domain Name System), SNMP (the Simple Network Management Protocol), and various others noted by Stevens [194]. It is also

Page 131: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

likely to continue to figure prominently in some modern performance-intensive roles such as multimedia.

Strictly speaking, UDP is a ``connectionless'' protocol--a program can use a single UDP socket to communicate with more than one host and port number--but it is convenient for most UDP client programs to maintain the fiction that there is a connection, by keeping a local record of each server host and port number.

Send datagram on UDP server socket

proc sendto (stringf, stringaddress, stringdatagram) proc sendto (integerf, stringaddress, stringdatagram)

The datagram is sent by the UDP server socket f to the destination address, which should be formatted as a string of the form "ip.name.or.address:portnum". The select procedure may be used to check or wait for f to be ready to take a datagram.

Receive datagram on UDP client socket

op recv (stringf) : string op recv (integerf) : string

A datagram is read from the UDP client socket f and yielded as a string. The select procedure may be used to check or wait for input of this kind.

Receive datagram on UDP server socket

op recvfrom (stringf) : tuple op recvfrom (integerf) : tuple

A datagram is read from the UDP server socket f, and its its sender's address is sensed. The address is formatted as a string of the form "ip.address:portnum", and returned with the datagram as the pair of strings [address, datagram]. Example of use:

[address, datagram] := recvfrom f;

Send datagram on UDP client socket

proc send (stringf, stringdatagram) proc send (integerf, stringdatagram)

The datagram is sent to the UDP client socket f. The select procedure may be used to check or wait for f to be ready to take a datagram

Page 132: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Echo client & server The aim for this example is to run a client which accepts typed input and this is printed out on the server on stdout

The echo functionality is represented in the following very short IDL.

Example Echo IDL file

// MyFirstOrbit program - The Echo object // // All this does is pass a string from the // client to the server. interface Echo { void echoString(in string input); };

The interface definition is the key part of the definition. Each interface defines an object which can have methods on it. In this case there is one method, which takes a string argument and returns nothing. The in declaration before the argument indicates that this arguments is only passed into the method. Generally all arguments are in arguments, for the first case.

This idl is found in the file echo.idl. To compile the idl one does the following step: $ orbit-idl-2 --skeleton-impl echo.idlwhich will produce most of the needed files to start writing the echo application (you can see it as a framework). They are listed in the following table:

File Usage for Client Usage for Server echo.h readonly readonly echo-common.c readonly readonly echo-stubs.c readonly - echo-skels.c - readonly echo-skelimpl.c - template for user codeFiles remaining to write are listed in following table, starting with echo-client.c in following chapter. echo-client.c write the client code echo-server.c write the generic code for servant creation

Echo client The client code is shown here

Page 133: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Example echo-client.c

/* * Echo client program.. Hacked by Ewan Birney <[email protected]> * from echo test suite, update for ORBit2 by Frank Rehberger * <[email protected]> * * Client reads object reference (IOR) from local file 'echo.ref' and * forwards console input to echo-server. A dot . as single character * in input terminates the client. */ #include <stdio.h> #include <signal.h> #include <orbit/orbit.h> /* * This header file was generated from the idl */ #include "echo.h" /** * test for exception */ static gboolean raised_exception(CORBA_Environment *ev) { return ((ev)->_major != CORBA_NO_EXCEPTION); } /** * in case of any exception this macro will abort the process */ static void abort_if_exception(CORBA_Environment *ev, const char* mesg) { if (raised_exception (ev)) { g_error ("%s %s", mesg, CORBA_exception_id (ev)); CORBA_exception_free (ev); abort(); } } static CORBA_ORB global_orb = CORBA_OBJECT_NIL; /* global orb */ /* Is called in case of process signals. it invokes CORBA_ORB_shutdown() * function, which will terminate the processes main loop. */ static void client_shutdown (int sig) {

Page 134: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

CORBA_Environment local_ev[1]; CORBA_exception_init(local_ev); if (global_orb != CORBA_OBJECT_NIL) { CORBA_ORB_shutdown (global_orb, FALSE, local_ev); abort_if_exception (local_ev, "caught exception"); } } /* Inits ORB @orb using @argv arguments for configuration. For each * ORBit options consumed from vector @argv the counter of @argc_ptr * will be decremented. Signal handler is set to call * echo_client_shutdown function in case of SIGINT and SIGTERM * signals. If error occures @ev points to exception object on * return. */ static void client_init (int *argc_ptr, char *argv[], CORBA_ORB *orb, CORBA_Environment *ev) { /* init signal handling */ signal(SIGINT, client_shutdown); signal(SIGTERM, client_shutdown); /* create Object Request Broker (ORB) */ (*orb) = CORBA_ORB_init(argc_ptr, argv, "orbit-local-mt-orb", ev); if (raised_exception(ev)) return; } /* Releases @servant object and finally destroys @orb. If error * occures @ev points to exception object on return. */ static void client_cleanup (CORBA_ORB orb, CORBA_Object service, CORBA_Environment *ev) { /* releasing managed object */ CORBA_Object_release(service, ev); if (raised_exception(ev)) return; /* tear down the ORB */ if (orb != CORBA_OBJECT_NIL) { /* going to destroy orb.. */ CORBA_ORB_destroy(orb, ev); if (raised_exception(ev)) return; }

Page 135: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

} /** * */ static CORBA_Object client_import_service_from_stream (CORBA_ORB orb, FILE *stream, CORBA_Environment *ev) { CORBA_Object obj = CORBA_OBJECT_NIL; gchar *objref=NULL; fscanf (stream, "%as", &objref); /* FIXME, handle input error */ obj = (CORBA_Object) CORBA_ORB_string_to_object (global_orb, objref, ev); free (objref); return obj; } /** * */ static CORBA_Object client_import_service_from_file (CORBA_ORB orb, char *filename, CORBA_Environment *ev) { CORBA_Object obj = NULL; FILE *file = NULL; /* write objref to file */ if ((file=fopen(filename, "r"))==NULL) g_error ("could not open %s\n", filename); obj=client_import_service_from_stream (orb, file, ev); fclose (file); return obj; } /** * */ static void client_run (Echo echo_service, CORBA_Environment *ev)

Page 136: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

{ char filebuffer[1024+1]; g_print("Type messages to the server\n" "a single dot in line will terminate input\n"); while( fgets(filebuffer,1024,stdin) ) { if( filebuffer[0] == '.' && filebuffer[1] == '\n' ) break; /* chop the newline off */ filebuffer[strlen(filebuffer)-1] = '\0'; /* using the echoString method in the Echo object * this is defined in the echo.h header, compiled from * echo.idl */ Echo_echoString(echo_service,filebuffer,ev); if (raised_exception (ev)) return; } } /* * main */ int main(int argc, char* argv[]) { CORBA_char filename[] = "echo.ref"; Echo echo_service = CORBA_OBJECT_NIL; CORBA_Environment ev[1]; CORBA_exception_init(ev); client_init (&argc, argv, &global_orb, ev); abort_if_exception(ev, "init failed"); g_print ("Reading service reference from file \"%s\"\n", filename); echo_service = (Echo) client_import_service_from_file (global_orb, "echo.ref", ev); abort_if_exception(ev, "import service failed"); client_run (echo_service, ev); abort_if_exception(ev, "service not reachable"); client_cleanup (global_orb, echo_service, ev); abort_if_exception(ev, "cleanup failed"); exit (0); } The client can be broken down into three distinct sections.

Page 137: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

• Initialising the ORB • Getting the Object • Using the Object

The key part of the client is when it calls the echoString method on the server. The idl definition void echoString(in string input); Ends up becoming the following definition in the echo.h header file generated from the idl extern void Echo_echoString(Echo obj, CORBA_char *astring, CORBA_Environment *ev); This follows the accepted rules for Object based programming in C, that is

• The Object is passed in as the first argument to the function • The method name is qualified by the object name beforehand • Exceptions are handled by a structure that is passed in as the last argument to the function

Of course, you don't have to follow this in your own code, but this is how the CORBA C mapping works, and it is not a bad solution.

Echo Server The server is basically more complicated than the client, but has some commonality with the client. The server has to at the end of the day go into a main loop where it listens to connections. Before that it has to create the ORB and bind its own implementations of the objects to the ORB.

In real life servers, this gets much more complicated, but as this is an example, it is pretty simple once you get through the ORB initialisation process.

Example echo-server.c source code

/* * echo-server program. Hacked from Echo test suite by * <[email protected]>, ORBit2 udpate by Frank Rehberger * <[email protected]> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <orbit/orbit.h> #include "echo-skelimpl.c" #include "examples-toolkit.h" /* provides etk_abort_if_exception */ static CORBA_ORB global_orb = CORBA_OBJECT_NIL; /* global orb */ static PortableServer_POA root_poa = CORBA_OBJECT_NIL; /* root POA /* Is called in case of process signals. it invokes CORBA_ORB_shutdown()

Page 138: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

* function, which will terminate the processes main loop. */ static void server_shutdown (int sig) { CORBA_Environment local_ev[1]; CORBA_exception_init(local_ev); if (global_orb != CORBA_OBJECT_NIL) { CORBA_ORB_shutdown (global_orb, FALSE, local_ev); etk_abort_if_exception (local_ev, "caught exception"); } } /* Inits ORB @orb using @argv arguments for configuration. For each * ORBit options consumed from vector @argv the counter of @argc_ptr * will be decremented. Signal handler is set to call * echo_server_shutdown function in case of SIGINT and SIGTERM * signals. If error occures @ev points to exception object on * return. */static void server_init (int *argc_ptr, char *argv[], CORBA_ORB *orb, PortableServer_POA *poa, CORBA_Environment *ev) { PortableServer_POAManager poa_manager = CORBA_OBJECT_NIL; CORBA_Environment local_ev[1]; CORBA_exception_init(local_ev); /* init signal handling */ signal(SIGINT, server_shutdown); signal(SIGTERM, server_shutdown); /* create Object Request Broker (ORB) */ (*orb) = CORBA_ORB_init(argc_ptr, argv, "orbit-local-mt-orb", ev); if (etk_raised_exception(ev)) goto failed_orb; (*poa) = (PortableServer_POA) CORBA_ORB_resolve_initial_references(*orb, "RootPOA", ev); if (etk_raised_exception(ev)) goto failed_poa; poa_manager = PortableServer_POA__get_the_POAManager(*poa, ev); if (etk_raised_exception(ev)) goto failed_poamanager; PortableServer_POAManager_activate(poa_manager, ev); if (etk_raised_exception(ev))

Page 139: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

goto failed_activation; CORBA_Object_release ((CORBA_Object) poa_manager, ev); return; failed_activation: failed_poamanager: CORBA_Object_release ((CORBA_Object) poa_manager, local_ev); failed_poa: CORBA_ORB_destroy(*orb, local_ev); failed_orb: return; } /* Entering main loop @orb handles incoming request and delegates to * servants. If error occures @ev points to exception object on * return. */ static void server_run (CORBA_ORB orb, CORBA_Environment *ev) { /* enter main loop until SIGINT or SIGTERM */ CORBA_ORB_run(orb, ev); if (etk_raised_exception(ev)) return; /* user pressed SIGINT or SIGTERM and in signal handler * CORBA_ORB_shutdown(.) has been called */ } /* Releases @servant object and finally destroys @orb. If error * occures @ev points to exception object on return. */ static void server_cleanup (CORBA_ORB orb, PortableServer_POA poa, CORBA_Object ref, CORBA_Environment *ev) { PortableServer_ObjectId *objid = NULL; objid = PortableServer_POA_reference_to_id (poa, ref, ev); if (etk_raised_exception(ev)) return; /* Servant: deactivatoin - will invoke __fini destructor */ PortableServer_POA_deactivate_object (poa, objid, ev); if (etk_raised_exception(ev)) return; PortableServer_POA_destroy (poa, TRUE, FALSE, ev); if (etk_raised_exception(ev)) return; CORBA_free (objid); CORBA_Object_release ((CORBA_Object) poa, ev); if (etk_raised_exception(ev)) return;

Page 140: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

CORBA_Object_release (ref, ev); if (etk_raised_exception(ev)) return; /* ORB: tear down the ORB */ if (orb != CORBA_OBJECT_NIL) { /* going to destroy orb.. */ CORBA_ORB_destroy(orb, ev); if (etk_raised_exception(ev)) return; } } /* Creates servant and registers in context of ORB @orb. The ORB will * delegate incoming requests to specific servant object. @return * object reference. If error occures @ev points to exception object * on return. */ static CORBA_Object server_activate_service (CORBA_ORB orb, PortableServer_POA poa, CORBA_Environment *ev) { Echo ref = CORBA_OBJECT_NIL; ref = impl_Echo__create (poa, ev); if (etk_raised_exception(ev)) return CORBA_OBJECT_NIL; return ref; } /* * main */ int main (int argc, char *argv[]) { CORBA_Object servant = CORBA_OBJECT_NIL; CORBA_char filename[] = "echo.ref"; CORBA_Environment ev[1]; CORBA_exception_init(ev); server_init (&argc, argv, &global_orb, &root_poa, ev); etk_abort_if_exception(ev, "failed ORB init"); servant = server_activate_service (global_orb, root_poa, ev); etk_abort_if_exception(ev, "failed activating service"); g_print ("Writing service reference to: %s\n\n", filename); etk_export_object_to_file (global_orb, servant,

Page 141: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

filename, ev); etk_abort_if_exception(ev, "failed exporting IOR"); server_run (global_orb, ev); etk_abort_if_exception(ev, "failed entering main loop"); server_cleanup (global_orb, root_poa, servant, ev); etk_abort_if_exception(ev, "failed cleanup"); exit (0); }

The key part of the server is when it calls servant = impl_Echo__create (poa, ev);. This is a function defined in file echo-skelimpl.c being included at top of echo-server.c. For each object method of echo object interface file echo-skelimpl.c contains a predefined implementation that must be extended by user (specific regions are marked by comments); incoming requests are delegated by object manager to specific method implementation. - For echo server application only a single line for method echoString(..) must be inserted, this line will print the echo-string to console. Let's have a look at echo-skelimpl.c that has been generated by orbit-idl-2 tool as template for user. Therefor only a single line has been added by user g_print ("%s\n", input); at very end of file in function body impl_Echo_echoString(..).

Constructor (__create) and Destructor (__fini) are defined, too. How to extend those functions defining lifecycle of objects will be subject to next chapters.

Example echo-skelimpl.c

#include "echo.h" /*** App-specific servant structures ***/ typedef struct { POA_Echo servant; PortableServer_POA poa; /* ------ add private attributes here ------ */ /* ------ ---------- end ------------ ------ */ } impl_POA_Echo; /*** Implementation stub prototypes ***/ static void impl_Echo__fini(impl_POA_Echo * servant, CORBA_Environment * ev); static void impl_Echo_echoString(impl_POA_Echo * servant, const CORBA_char * input, CORBA_Environment * ev);

Page 142: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

/*** epv structures ***/ static PortableServer_ServantBase__epv impl_Echo_base_epv = { NULL, /* _private data */ (gpointer) &amp; impl_Echo__fini, /* finalize routine */ NULL, /* default_POA routine */ }; static POA_Echo__epv impl_Echo_epv = { NULL, /* _private */ (gpointer) & impl_Echo_echoString, }; /*** vepv structures ***/ static POA_Echo__vepv impl_Echo_vepv = { &impl_Echo_base_epv, &impl_Echo_epv, }; /*** Stub implementations ***/ static Echo impl_Echo__create(PortableServer_POA poa, CORBA_Environment * ev) { Echo retval; impl_POA_Echo *newservant; PortableServer_ObjectId *objid; newservant = g_new0(impl_POA_Echo, 1); newservant->servant.vepv = &impl_Echo_vepv; newservant->poa = (PortableServer_POA) CORBA_Object_duplicate((CORBA_Object) poa, ev); POA_Echo__init((PortableServer_Servant) newservant, ev); /* Before servant is going to be activated all * private attributes must be initialized. */ /* ------ init private attributes here ------ */ /* ------ ---------- end ------------- ------ */ objid = PortableServer_POA_activate_object(poa, newservant, ev); CORBA_free(objid); retval = PortableServer_POA_servant_to_reference(poa, newservant, ev); return retval; } static void impl_Echo__fini(impl_POA_Echo * servant, CORBA_Environment * ev) { CORBA_Object_release((CORBA_Object) servant->poa, ev); /* No further remote method calls are delegated to * servant and you may free your private attributes. */ /* ------ free private attributes here ------ */ /* ------ ---------- end ------------- ------ */

Page 143: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

POA_Echo__fini((PortableServer_Servant) servant, ev); g_free(servant); } static void impl_Echo_echoString(impl_POA_Echo * servant, const CORBA_char * input, CORBA_Environment * ev) { /* ------ insert method code here ------ */ g_print ("%s\n", input); /* ------ ---------- end ------------ ------ */ }

Compiling server & client The following makefile can be used to compile both, the client and the server. Be aware of the location of ORBit : on my system it has been installed under /usr but it could be /usr/local if you have built it from the sources, and hence the path for ORBIT variables below may vary. If using ORBit binary packages shipped with your Linux or BSD/Unix distribution the makefile below will do.

Example Makefile

PREFIX ?= /usr CC = gcc TARGETS=echo-client echo-server ORBIT_IDL=orbit-idl-2 CFLAGS=-g -DORBIT2=1 -D_REENTRANT -I$(PREFIX)/include/orbit-2.0 \ -I$(PREFIX)/include/linc-1.0 -I$(PREFIX)/include/glib-2.0 \ -I$(PREFIX)/lib/glib-2.0/include LDFLAGS= -Wl,--export-dynamic -L$(PREFIX)/lib -lORBit-2 -llinc -lgmodule-2.0 \ -ldl -lgobject-2.0 -lgthread-2.0 -lpthread -lglib-2.0 -lm IDLOUT=echo-common.c echo-stubs.c echo-skels.c echo.h all: $(IDLOUT) echo-client echo-server echo-server.o : echo-server.c echo-skelimpl.c echo-client : echo-client.o echo-common.o echo-stubs.o echo-server : echo-server.o echo-common.o echo-skels.o $(IDLOUT): echo.idl $(ORBIT_IDL) echo.idl clean: rm -rf *.o *~ $(IDLOUT) distclean: clean rm -rf echo-client echo-server

Page 144: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Example Invoking make

[frehberg@papaya echo]$ make orbit-idl-2 echo.idl orbit-idl-2 2.4.1 compiling small mode, show preprocessor errors, passes: stubs skels common headers skel_impl imodule gcc -DORBIT2=1 -D_REENTRANT -I/usr/include/orbit-2.0 -I/usr/include/linc-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -c -o echo-client.o echo-client.c gcc -DORBIT2=1 -D_REENTRANT -I/usr/include/orbit-2.0 -I/usr/include/linc-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -c -o echo-common.o echo-common.c gcc -DORBIT2=1 -D_REENTRANT -I/usr/include/orbit-2.0 -I/usr/include/linc-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -c -o echo-stubs.o echo-stubs.c gcc -Wl,--export-dynamic -lORBit-2 -llinc -lgmodule-2.0 -ldl -lgobject-2.0 -lgthread-2.0 -lpthread -lglib-2.0 -lm echo-client.o echo-common.o echo-stubs.o -o echo-client gcc -DORBIT2=1 -D_REENTRANT -I/usr/include/orbit-2.0 -I/usr/include/linc-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -c -o echo-server.o echo-server.c gcc -DORBIT2=1 -D_REENTRANT -I/usr/include/orbit-2.0 -I/usr/include/linc-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -c -o echo-skels.o echo-skels.c gcc -Wl,--export-dynamic -lORBit-2 -llinc -lgmodule-2.0 -ldl -lgobject-2.0 -lgthread-2.0 -lpthread -lglib-2.0 -lm echo-server.o echo-common.o echo-skels.o -o echo-server

After calling make in terminal window all sources have been compiled and you should open a second terminal window. In the first window we will start the server with the command: ./echo-server. The server should print a very long string into the file echo.ref, starting with the 4 character sequence IOR: In the second window we will print content of echo.ref to console and start the client with the command ./echo-client. You should not try to type the IOR string, instead use the cut and paste functionality of your terminal.

Example Terminal 1 - Starting Echo Server

[frehberg@papaya echo]$ ./echo-server

Example Terminal 2 - Starting Echo Client

[frehberg@papaya echo]$ cat echo.ref IOR:010000000d00000049444c3a4563686f3a312e3000000000030000000054424f540000000101 020005000000554e4958000000000700000070617061796100002e0000002f746d702f6f72626974 2d66726568626572672f6c696e632d323230662d302d323532356663323537306430340000000000 0000caaedfba58000000010102002e0000002f746d702f6f726269742d66726568626572672f6c69

Page 145: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

6e632d323230662d302d323532356663323537306430340000001c00000000000000a6361450d7ea e8a8dc29282828282828010000008af91bdf01000000480000000100000002000000050000001c00 000000000000a6361450d7eae8a8dc29282828282828010000008af91bdf01000000140000000100 000001000105000000000901010000000000 [frehberg@papaya echo]$ ./echo-client Type messages to the server a single dot in line will terminate input:

Name and Address Conversions

UNIT V

Daemon Processes

When you run an editor it is easy to control the editor, tell it to load files, and so on. You can do this because the editor provides facilities to do so, and because the editor is attached to a terminal. Some programs are not designed to be run with continuous user input, and so they disconnect from the terminal at the first opportunity. For example, a web server spends all day responding to web requests; it normally does not need any input from you. Programs that transport email from site to site are another example of this class of application.

We call these programs daemons. Daemons were characters in Greek mythology: neither good nor evil, they were little attendant spirits that, by and large, did useful things for mankind, much like the web servers and mail servers of today do useful things. This is why the BSD mascot has, for a long time, been the cheerful-looking daemon with sneakers and a pitchfork.

There is a convention to name programs that normally run as daemons with a trailing “d”. BIND is the Berkeley Internet Name Domain, but the actual program that executes is called named; the Apache web server program is called httpd; the line printer spooling daemon is lpd and so on. This is a convention, not a hard and fast rule; for example, the main mail daemon for the Sendmail application is called sendmail, and not maild, as you might imagine.

Sometimes you will need to communicate with a daemon process. One way to do so is to send it (or any other running process), what is known as a signal. There are a number of different signals that you can send—some of them have a specific meaning, others are interpreted by the application, and the application's documentation will tell you how that application interprets signals. You can only send a signal to a process that you own. If you send a signal to someone else's process with kill (1) or kill(2), permission will be denied. The exception to this is the root user, who can send signals to everyone's processes.

Page 146: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

FreeBSD will also send applications signals in some cases. If an application is badly written, and tries to access memory that it is not supposed to, FreeBSD sends the process the Segmentation Violation signal (SIGSEGV). If an application has used the alarm(3) system call to be alerted after a period of time has elapsed then it will be sent the Alarm signal (SIGALRM), and so on.

Two signals can be used to stop a process, SIGTERM and SIGKILL. SIGTERM is the polite way to kill a process; the process can catch the signal, realize that you want it to shut down, close any log files it may have open, and generally finish whatever it is doing at the time before shutting down. In some cases a process may even ignore SIGTERM if it is in the middle of some task that can not be interrupted.

SIGKILL can not be ignored by a process. This is the “I do not care what you are doing, stop right now” signal. If you send SIGKILL to a process then FreeBSD will stop that process there and then[1].

The other signals you might want to use are SIGHUP, SIGUSR1, and SIGUSR2. These are general purpose signals, and different applications will do different things when they are sent.

Suppose that you have changed your web server's configuration file—you would like to tell the web server to re-read its configuration. You could stop and restart httpd, but this would result in a brief outage period on your web server, which may be undesirable. Most daemons are written to respond to the SIGHUP signal by re-reading their configuration file. So instead of killing and restarting httpd you would send it the SIGHUP signal. Because there is no standard way to respond to these signals, different daemons will have different behavior, so be sure and read the documentation for the daemon in question.

Signals are sent using the kill(1) command, as this example shows.

INETD Superserver

Sending a Signal to a Process

This example shows how to send a signal to inetd(8). The inetd configuration file is /etc/inetd.conf, and inetd will re-read this configuration file when it is sent SIGHUP.

1. Find the process ID of the process you want to send the signal to. Do this using ps(1) and grep(1). The grep(1) command is used to search through output, looking for the string you specify. This command is run as a normal user, and inetd(8) is run as root, so the ax options must be given to ps(1).

2. % ps -ax | grep inetd

3. 198 ?? IWs 0:00.00 inetd -wW

Page 147: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

So the inetd(8) PID is 198. In some cases the grep inetd command might also appear in this output. This is because of the way ps(1) has to find the list of running processes.

4. Use kill(1) to send the signal. Because inetd(8) is being run by root you must use su(1) to become root first.

5. % su

6. Password:

7. # /bin/kill -s HUP 198

In common with most UNIX® commands, kill(1) will not print any output if it is successful. If you send a signal to a process that you do not own then you will see “kill: PID: Operation not permitted”. If you mistype the PID you will either send the signal to the wrong process, which could be bad, or, if you are lucky, you will have sent the signal to a PID that is not currently in use, and you will see “kill: PID: No such process”.

Sending other signals is very similar, just substitute TERM or KILL in the command line as necessary.

Multicasting

Broadcasting

In computer networking, broadcasting refers to transmitting a packet that will be received by every device on the network.[1] In practice, the scope of the broadcast is limited to a broadcast domain. Broadcast a message is in contrast to unicast addressing in which a host sends datagrams to another single host identified by a unique IP address.

Not all network technologies support broadcast addressing; for example, neither X.25 nor frame relay have broadcast capability, nor is there any form of Internet-wide broadcast. Broadcasting is largely confined to local area network (LAN) technologies, most notably Ethernet and token ring, where the performance impact of broadcasting is not as large as it would be in a wide area network.

The successor to Internet Protocol Version 4 (IPv4), IPv6 also does not implement the broadcast method, so as to prevent disturbing all nodes in a network when only a few may be interested in a particular service. Instead it relies on multicast addressing a conceptually similar one-to-many routing methodology. However, multicasting limits the pool of receivers to those that join a specific multicast receiver group.

Both Ethernet and IPv4 use an all-ones broadcast address to indicate a broadcast packet. Token Ring uses a special value in the IEEE 802.2 control field.

Page 148: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Broadcasting may be abused to perform a DoS-attack. The attacker sends fake ping request with the source IP-address of the victim computer. The victim computer is flooded by the replies from all computers in the domain.

Out-of-band data

Out-of-band data

Out-of-band (OOB) data is user-specific data that only has meaning for connection-oriented (stream) sockets. Stream data is generally received in the same order it is sent. OOB data is received independent of its position in the stream (independent of the order in which it was sent). This is possible because the data is marked in such a way that, when it is sent from program A to program B, program B is notified of its arrival.

OOB data is supported on AF_INET (SOCK_STREAM) and AF_INET6 (SOCK_STREAM) only.

OOB data is sent by specifying the MSG_OOB flag on the send(), sendto(), and sendmsg() functions.

The transmission of OOB data is the same as the transmission of regular data. It is sent after any data that is buffered. In other words, OOB data does not take precedence over any data that may be buffered; data is transmitted in the order that it was sent.

On the receiving side, things are a little more complex:

• The sockets API keeps track of OOB data that is received on a system by using an OOB marker. The OOB marker points to the last byte in the OOB data that was sent.

Note: The value that indicates which byte the OOB marker points to is set on a system basis (all applications use that value). This value must be consistent between the local and remote ends of a TCP connection. Socket applications that use this value must use it consistently between the client and server applications. To change which byte the OOB marker points to, see Change TCP Attributes (CHGTCPA) command in the Information Center.

The SIOCATMARK ioctl() request determines if the read pointer is pointing to the last OOB byte.

Note:

Page 149: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

If multiple occurrences of OOB data are sent, the OOB marker points to the last OOB byte of the final OOB data occurrence.

• Independent of whether OOB data is received in-line or not, an input operation processes data up to the OOB marker, if OOB data was sent.

• A recv(), recvmsg(), or recvfrom() function (with the MSG_OOB flag set) is used to receive OOB data. An error of [EINVAL] is returned if one of the receive functions has completed and one of the following occurs:

o The socket option SO_OOBINLINE is not set and there is no OOB data to receive.

o The socket option SO_OOBINLINE is set.

If the socket option SO_OOBINLINE is not set, and the sending program sent OOB data with size greater than one byte, all the bytes but the last are considered normal data. (Normal data means that the receiving program can receive data without specifying the MSG_OOB flag.) The last byte of the OOB data that was sent is not stored in the normal data stream. This byte can only be retrieved by issuing a recv(), recvmsg(), or recvfrom() function with the MSG_OOB flag set. If a receive is issued with the MSG_OOB flag not set, and normal data is received, the OOB byte is deleted. Also, if multiple occurrences of OOB data are sent, the OOB data from the preceding occurrence is lost, and the position of the OOB data of the final OOB data occurrence is remembered.

If the socket option SO_OOBINLINE is set, then all of the OOB data that was sent is stored in the normal data stream. Data can be retrieved by issuing one of the three receive functions without specifying the MSG_OOB flag (if it is specified, an error of [EINVAL] is returned). OOB data is not lost if multiple occurrences of OOB data are sent.

• OOB data is not discarded if SO_OOBINLINE is not set, OOB data has been received, and the user then sets SO_OOBINLINE on. The initial OOB byte is considered normal data.

• If SO_OOBINLINE is not set, OOB data was sent, and the receiving program issued an input function to receive the OOB data, then the OOB marker is still valid. The receiving program can still check if the read pointer is at the OOB marker, even though the OOB byte was received.

Raw sockets

Name raw, SOCK_RAW - Linux IPv4 rawsockets Synopsis #include <sys/socket.h> #include <netinet/in.h> raw_socket = socket(AF_INET, SOCK_RAW, intprotocol);

Page 150: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Description Rawsockets allow new IPv4 protocols to be implemented in user space. A raw socket receives or sends the raw datagram not including link level headers.

The IPv4 layer generates an IP header when sending a packet unless the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving the IP header is always included in the packet.

Only processes with an effective user ID of 0 or the CAP_NET_RAW capability are allowed to open rawsockets.

All packets or errors matching the protocol number specified for the raw socket are passed to this socket. For a list of the allowed protocols see RFC 1700 assigned numbers and getprotobyname(3).

A protocol of IPPROTO_RAW implies enabled IP_HDRINCL and is able to send any IP protocol that is specified in the passed header. Receiving of all IP protocols via IPPROTO_RAW is not possible using rawsockets.

IP Header fields modified on sending by IP_HDRINCL IP Checksum Always filled in. Source Address Filled in when zero. Packet Id Filled in when zero. Total Length Always filled in.

If IP_HDRINCL is specified and the IP header has a nonzero destination address then the destination address of the socket is used to route the packet. When MSG_DONTROUTE is specified, the destination address should refer to a local interface, otherwise a routing table lookup is done anyway but gatewayed routes are ignored.

If IP_HDRINCL isn't set, then IP header options can be set on rawsockets with setsockopt(2); see ip(7) for more information.

In Linux 2.2, all IP header fields and options can be set using IP socket options. This means rawsockets are usually only needed for new protocols or protocols with no user interface (like ICMP).

When a packet is received, it is passed to any rawsockets which have been bound to its protocol before it is passed to other protocol handlers (e.g., kernel protocol modules).

Address Format Rawsockets use the standard sockaddr_in address structure defined in ip(7). The sin_port field could be used to specify the IP protocol number, but it is ignored for sending in Linux 2.2 and should be always set to 0 (see BUGS). For incoming packets, sin_port is set to the protocol of the packet. See the <netinet/in.h> include file for valid IP protocols.

Socket Options Raw socket options can be set with setsockopt(2) and read with getsockopt(2) by passing the IPPROTO_RAW family flag. ICMP_FILTER

Page 151: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

Enable a special filter for rawsockets bound to the IPPROTO_ICMP protocol. The value has a bit set for each ICMP message type which should be filtered out. The default is to filter no ICMP messages.

In addition, all ip(7)IPPROTO_IP socket options valid for datagram sockets are supported.

Error Handling Errors originating from the network are only passed to the user when the socket is connected or the IP_RECVERR flag is enabled. For connected sockets, only EMSGSIZE and EPROTO are passed for compatibility. With IP_RECVERR, all network errors are saved in the error queue. Errors EACCES

User tried to send to a broadcast address without having the broadcast flag set on the socket. EFAULT

An invalid memory address was supplied. EINVAL

Invalid argument. EMSGSIZE

Packet too big. Either Path MTU Discovery is enabled (the IP_MTU_DISCOVER socket flag) or the packet size exceeds the maximum allowed IPv4 packet size of 64KB.

EOPNOTSUPP Invalid flag has been passed to a socket call (like MSG_OOB).

EPERM The user doesn't have permission to open rawsockets. Only processes with an effective user ID of 0 or the CAP_NET_RAW attribute may do that.

EPROTO An ICMP error has arrived reporting a parameter problem.

Versions IP_RECVERR and ICMP_FILTER are new in Linux 2.2. They are Linux extensions and should not be used in portable programs.

Linux 2.0 enabled some bug-to-bug compatibility with BSD in the raw socket code when the SO_BSDCOMPAT socket option was set -- since Linux 2.2, this option no longer has that effect.

Data Link Access

DCAP: Data Link Switching Client Access Protocol

CR-LDP, constraint-based LDP, is one of the The Data Link Switching Client Access Protocol (DCAP) is an application layer protocol used between workstations and routers to transport SNA/NetBIOS traffic over TCP sessions.

DCAP was introduced to address a few deficiencies by the Data Link Switching Protocol (DLSw). The implementation of Data Link Switching Protocol (DLSw) on a large number of workstations raises the important issues of scalability and efficiency. Since DLSw is a switch-to-switch protocol, it is not efficient when implemented on workstations. DCAP addresses these issues. It introduces a hierarchical structure to resolve the scalability problems. All workstations are clients to the router (server) rather than peers to the router. This creates a client/server model. It also provides a more efficient protocol between the workstation (client) and the router (server).

Page 152: Unix and network Programming MC0618 - SRM Institute of ...unix and network... · Unix and network Programming MC0618 ... File I/O – study of open, close, read, write, lseek,

Unix and network Programming MC0618  2012 

SRM University Department of Computer Applications S.Kanchana Devi

In a DLSw network, each workstation needs a MAC address to communicate with a FEP attached to a LAN. When DLSw is implemented on a workstation, it does not always have a MAC address defined. For example, when a workstation connects to a router through a modem via PPP, it only consists of an IP address. In this case, the user must define a virtual MAC address. This is administratively intensive since each workstation must have an unique MAC address. DCAP uses the Dynamic Address Resolution protocol to solve this problem. The Dynamic Address Resolution protocol permits the server to dynamically assign a MAC address to a client without complex configuration.

Protocol Structure - DCAP (Data Link Switching Client Access Protocol)

4 8 16bit

Protocol ID Version Number Message Type

Packet Length

• Protocol ID - The Protocol ID is set to 1000. • Version number - The Version number is set to 0001. • Message type - The message type is the DCAP message type. • Packet length - The total packet length is the length of the packet including the DCAP

header, DCAP data and user data. The minimum size of the packet is 4, which is the length of the header.

-----------------------------------------------------------------------------