chapter 12 advanced programming: systems calls by c. shing itec dept radford university

128
Chapter 12 Advanced Programming: Systems Calls By C. Shing ITEC Dept Radford University

Upload: elmer-anthony

Post on 19-Jan-2016

243 views

Category:

Documents


0 download

TRANSCRIPT

Chapter 12 Advanced Programming: Systems Calls

By C. Shing

ITEC Dept

Radford University

Slide 2

Objectives Understand the capabilities of system calls Understand how to use system calls for

file and process management Understand the signals and how to control

processes

Slide 3

System Calls Programmer’s interface to kernel Capabilities: function returns -1 if failed

– Error handling: library routine - perror()– File management– Process management

Slide 4

System Calls (Cont.) File management

Regular:

open(), close(), read(), write(), lseek() – in Chapter 7

link(), unlink(), chmod(), chown(), dup(), dup2(),

fcntl(), stat(), fstat(), truncate(), ftruncate(), sync()

Slide 5

System Calls (Cont.) File management (Cont.)

Directory: getdents() Special (IPC):

o mknod(), ioctl(), pipe()o Sockets:

o accept(), bind(), connect(), listen(), socke()o Internet sockets:

gethostbyname(), gethostname(), htonl(),

htons(), inet_addr(), inet_ntoa()

Slide 6

System Calls (Cont.) Process management:

fork(), exec(), wait(), exit(), chdir(), setuid(),

setgid(), getuid(), getgid(), getpid(), getppid() Signals: kill()

Slide 7

Error Handling - perror Syntax: void perror (char *str)

Prints out :, followed by the description of error

after the string that you enter A standard C library routine

Must use #include <errno.h>

Description: Every process initialize a global variable errno when created errno stores error from last system call error Error number defined in /usr/include/sys/errno.h

Slide 8

Error Handling – perror (Cont.) Example: showErrno.c

Slide 9

Regular File Management - link Syntax: int link (const char *oldfilename,

const char *newaliase) Creates a hard link newaliase for oldfilename Both must be on same file system

Example: mylink.c

Slide 10

Regular File Management - unlink Syntax: int unlink (const char *filename)

Removes a hard link for filename. If , as a result,

no hard link exists, then the filename is de-allocated. An executable can unlink (or remove) itself during

execution.

Example: reverse.c

Slide 11

Regular File Management – chmod/fchmod

Syntax: int chmod (const char *filename,

int octal_permission)

int fchmod (int fd, int octal_permission) Change filename (fd) with octal_permission

Example: mychmod.c

Slide 12

Regular File Management – chown/lchown/fchown

Syntax: int chown (const char *filename, int ownerid, int groupid)

int lchown (const char *filename, int ownerid, int groupid)

int fchown (int fd, int ownerid, int groupid) chown/fchown: change ownerid and groupid for filename (fd) lchown: change ownerid and groupid for the link only

Example: mychown.c

Slide 13

Regular File Management – dup/dup2

Syntax: int dup (int oldfd)

int dup2 (int oldfd, int newfd) dup: creates a newfd and both fds point to same file dup2: creates a newfd and close the oldfd

Example: mydup.c

Slide 14

Regular File Management - fcntl Syntax: int fcntl (int fd, int flag, int mode)

Creates an action encoded by the flag on the file (fd)

with specified mode

Slide 15

Regular File Management - fcntl(Cont.) fcntl flags:

flag Explain

F_SETFD Set close-on-exec flag to lowest bit of mode

F_GETFD Return number with lowest bit 1 if close-on-exec flag is set. 0 otherwise

F_GETFL Return number with file status flag and access mode

F_SETFL Set file status flag to mode

Slide 16

Regular File Management - fcntl(Cont.) fcntl flags (Cont.):

flag Explain

F_GETOWN Return process id or process group that set to receive SIGIO/SIGURG signals

F_SETOWN set process id or process group that receive SIGIO/SIGURG signals to mode

Slide 17

Regular File Management – fcntl (Cont.)

Example: myfcntl.c

Slide 18

Regular File Management – stat/lstat/fstat

Syntax: int stat (const char *filename,

struct stat *buffer)

int lstat (const char *filename,

struct stat *buffer)

int fstat (int fd, struct stat *buffer) stat/fstat fill buffer with information about filename (fd)

in stat structure (defined in /usr/include/sys/stat.h) lstat fill buffer with information about the link only

Slide 19

Regular File Management – stat/lstat/fstat (Cont.)

stat structure:

Field Explain

st_dev Device nuimber

st_ino Inode number

st_mode Permission flags

st_nlink Hard link number

st_uid User id

st_gid Group id

Slide 20

Regular File Management – stat/lstat/fstat (Cont.)

stat structure (Cont.):

Field Explain

st_size File size

st_atime Last access time

st_mtime Last modified time

st_ctime Last status change time

Slide 21

Regular File Management – stat/lstat/fstat (Cont.)

Macro returns True using argument: st_mode in stat struct

Macro Explain

S_ISDIR A directory

S_ISCHR A character device

S_ISBLK A block device

S_ISREG A regular file

S_ISFIFO A pipe

Slide 22

Regular File Management – stat/lstat/fstat (Cont.)

Example: monitor.c

Slide 23

Regular File Management – truncate/ftruncate

Syntax: int truncate (const char *filename,

int length)

int f truncate (int fd, int length) Set size of filename (fd) to length bytes

Example: truncate.c

Slide 24

Regular File Management - sync Syntax: void sync (void)

Flush all file system buffers to be written to disks

Slide 25

Directory File Management – getdents/getdirectries

Syntax: int getdents (int fd, struct dirent *buffer,

int size) Read directory entry structure dirent into buffer address. Returns size of the directory entry if successful.

Slide 26

Directory File Management – getdents/getdirectries (Cont.)

dirent structure: defined in /usr/include/sys/dirent.h

Field Explain

d_ino Inode number

d_off Next directory entry offset

d_reclen Directory entry length

d_nam Filename length

Slide 27

Directory File Management – getdents/getdirectries (Cont.)

Example: truncate.c

count.c

Slide 28

Special File Management - mknod Syntax: int mknod (const char *filename,

mode_t type, dev_t device) Creates a regular, directory or special filename with type If filename is a character or block file, then low-order byte

of device specifies minor number and high-order byte

specifies major number

Slide 29

Special File Management – mknod (Cont.)

File type

Type Explain

S_ISDIR A directory

S_ISCHR A character device

S_ISBLK A block device

S_ISREG A regular file

S_ISFIFO A named pipe

Slide 30

Special File Management - ioctl Syntax: int ioctl (int fd, int cmd, int arg)

Performs operation on device encoded by cmd

with arg for cmd

Slide 31

Process Management – getpid, getppid

Syntax: pid_t getpid (void) Returns process id

Syntax: pid_t getppid (void) Returns parent’s process id

Slide 32

Process Management – exit Syntax: void exit (int status)

Deallocates process’ resources, sends a SIGCHLD signal

and waits for return code status to be accepted Status is 0-255

Example: myexit.c

Slide 33

Process Management - fork Syntax: pid_t fork (void)

Returns non-zero to parent process and zero to child process

Identify child process by checking the return value 0 Identify parent process by checking the return value non-zero

Example:if (fork() == 0) {// child process tasks}else {// parent process tasks}

Slide 34

Process Management – fork (Cont.) Example: myfork.c

Slide 35

Process Management – fork (Cont.) Comparison of parent and child processes

Common: child process has duplication of parent Code Data (e.g. file descriptor, process group) Stack

Difference Process id

Slide 36

Process Management – fork (Cont.) Child process becomes

Orphan process: parent dies before child,

automatically adopted by init process Example: orphan.c

Zombie process: parent suspend and

child is waiting for parent to accept its return code Example: zombie.c

Slide 37

Process Management – wait Syntax: pid_t wait (int *status)

Suspend the parent process until one child terminates Returns child process id and stores return code in status

Example: mywait.c

Slide 38

Process Management– execl/execv/execlp/execvp

Syntax: int execl (const char *filepath,

const char *argv[], NULL)

int execlp (const char *argv[], NULL)

int execv (const char *filepath,

const char **argv[])

int execvp (const char **argv[])

Slide 39

Process Management– execl/execv/execlp/execvp (Cont.)

Description argv[0] is the executable file that when executed,

it replaces the parent (i.e. calling) process All functions are library routines which invoke

system call exece execlp and execvp don’t specify file path

since they use environment variable $PATH to find executable

Slide 40

Process Management– execl/execv/execlp/execvp (Cont.)

Comparison example: exec family execl (“/bin/ls”, “ls”, “-l”, NULL); execlp (“ls”, “ls”, “-l”, NULL); char *cmd = {“ls”, “-l”};

execv (“/bin/ls”, cmd}; char *cmd = {“ls”, “-l”};

execvp (“ls”, cmd};

Slide 41

Process Management– execl/execv/execlp/execvp(Cont.)

execl Example: myexec.c

Slide 42

Process Management– execl/execv/execlp/execvp(Cont.)

execvp Example 1: create a background process

(process group changed)

steps:1. Create a child process to exec the background process

See background.c (background gcc mywait.c)

Slide 43

Process Management– execl/execv/execlp/execvp(Cont.)

Execvp (Cont.) Example 2: redirect output (ls -l > ls.out)

Steps:1. Open the right hand side of >

2. Duplicate fd from step 1 to stdout and close the fd.

In this way stdout will associate with this fd

4. exec the left hand side of >

See redirect.c (redirect ls.out ls –l)

Slide 44

Process Management – chdir Syntax: int chdir (const char *dirpath)

Set process’ working directory to address of dirpath

Example: mychdir.c

Slide 45

Process Management – nice Syntax: int nice (int decPriority)

Add priority level by decPriority It is library routine Priority level between -20 and +19 (high priority to low)

System and super-user processes priority levels are negative

If priority level over 19, then set to 19 Only super-user can make resulting priority level negative

Example: mynice.c

Slide 46

Process Management – getuid, getgid, getpgid

Syntax: uid_t getuid (void)

uid_t geteuid (void)

gid_t getgid (void)

gid_t getegid (void) Return calling process’ real (or effective) user (or group) id

Syntax: pid_t getpgid (pid_t pid) Return process’ group id of the process with the pid value

Slide 47

Process Management – setuid, setgid

Syntax: uid_t setuid (uid_t id)

uid_t seteuid (uid_t id)

gid_t setgid (gid_t id)

gid_t setegid (gid_t id) Change to id for calling process’ real (or effective)

user (or group) id

Syntax: pid_t setpgid (pid_t pid, pid_t pgid) set process’ group id of the process to pgid with the pid value

Slide 48

What is a Signal When interrupt occurs, kernel sends a signal

to the process One process can also send it to another process

if permitted Different kinds of signals are defined in

/usr/include/sys/signal.h

Slide 49

Signal Handler When process receives the signal, it suspends

current control flow and switch to signal hander.

When finisked, it resumes original control flow.

Slide 50

Signal Handler (Cont.) Two kinds of signal handler:

Kernel-supplied handler: core dump Quit process Ignore signal suspend process resume process

User-supplied handler

Slide 51

Process Management (Signal) – alarm

Syntax: unsigned alarm (unsigned count) Request kernel to send SIGALRM signal to calling process

after count seconds A standard C library routine

Example: alarm.c

Slide 52

Process Management (Signal) – pause

Syntax: int alarm (void) Suspend calling process until it receives the signal A standard C library routine

Example: alarm.c

Slide 53

Process Management (Signal) – signal Syntax: void *signal (int signalCode,

void *func(void)) Specify func when receives signalCode

SIG_IGN to ignore signal SIG_DFL for default kernel-supplied handler signalHandler name for user-supplied handler

except for signal SIGKILL and SIGSTP A standard C library routine signalCode is defined in /usr/include/signal.h

Example: handler.c

Slide 54

Process Management (Signal) – signal (Cont.)

Example: User-supplied handler: handler.c Kernel-supplied signal & Ignore signal:

critical.c

Slide 55

Process Management (Signal) – kill Syntax: int kill (pid_t pid, int signalCode)

Send the signalCode to the process with the pid value If pid=0, then signal sent to all process in the same group If pid=-1 and sender is super-user, then signal sent to

all processes including the sender If pid=-1 and sender is not super-user, then signal sent to

all processes owned by sender except the sender

If pid=negative except -1, then signal sent to all processes in the process group

Slide 56

Process Management (Signal) – kill (Cont.)

Example of using signal code: Suspend process

kill (pid, SIGSTOP);

Resume process

kill (pid, SIGCONT);

Slide 57

Process Management (Signal) – kill (Cont.)

Example: limit.c process groups of parent and child:

pgrp1.c pgrp2.c pgrp3.c

Slide 58

Pipe IPC on the same machine Establish between a write process and

a read process. Pipe has a read end and

a write end

Slide 59

Pipe (Cont.) Two kinds of pipes:

Unnamed pipe: 5K size,

1 write process and 1 read process Named pipe (System V only): 40 K size,

many write processes and 1 read process,

not work across network

Slide 60

Unnamed Pipe Creation: fd[0] is read end, fd[1] is write end

int fd[2];

pipe(fd);

Slide 61

Unnamed Pipe (Cont.) Use

1. Close read end of the write process before write

// for write process

close (fd[0]);

write (fd[1], buffer, length);

2. Close write end of the read process before read

// for read process

close (fd[1]);

read (fd[0], buffer, length);

Slide 62

Unnamed Pipe (Cont.) // for write process

1. if write size no more than pipe size, no pre-empt

2. if pipe read end close, write fails and send

SIGPIPE signal to terminate // for read process

1. if read more bytes than pipe has, return actual bytes

read

2. if write end open and read an empty pipe, suspend

read

3. if pipe write end close, read returns 0

Slide 63

Process Management – pipe Syntax: int pipe (int fd[2])

Create 2 file descriptors and stored in fd[0] and fd[1] lseek is not available for pipe

Example: talk.c

Slide 64

Process Management – pipe (Cont.) Unix shell: unnamed pipe

// for write process1. Close read end of the write process before write2. Duplicate write end to stdout3. Close write end so stdout will be used for write process4. Exec write process

// for read process1. Close write end of the read process before read2. Duplicate read end to stdin3. Close read end so stdin will be used for read process4. Exec read process

Example: connect.c (connect who wc)

Slide 65

Named Pipe (FIFO) Creation: use mknod to create a special file

and set right permission

mknod (“mypipe”, S_IFIFO, 0);

chmod (“mypipe”, 0660);

Slide 66

Named Pipe (FIFO) (Cont.) Use

// for read process1. Delete the pipe

unlink (“mypipe”);

2. Create the pipe

mknod (“mypipe”, S_IFIFO, 0);

chmod (“mypipe”, 0660);

3. Open the pipe for read

fd = open (“mypipe”, O_RDONLY);

4. start read process

read (fd, buffer, size);

Slide 67

Named Pipe (FIFO) (Cont.) Use (Cont.)

// for write process1. Open the pipe for write

fd = open (“mypipe”, O_WRONLY);

4. start write process

write (fd, buffer, size);

Slide 68

Named Pipe (FIFO) (Cont.) // for write process

1. if open a named pipe for write, butno process open for that file to write,write process suspend until a process open for the

file to read, unless O_NONBLOCK/O_NDELAY is set(in which open fails)

// for read process1. if open a named pipe for read, but

no process open for that file to write,read process suspend until a process open for the

file to write, unless O_NONBLOCK/O_NDELAY is set(in which open success)

Slide 69

Named Pipe (FIFO) (Cont.) Example: (reader & writer & writer &)

reader.c

writer.c

Slide 70

Socket IPC (two-way communication) across network Use client-server model:

server always runs as a background process (passive)

Client runs as foreground process (active) Defined in /usr/include/sys/socket.h

Slide 71

Socket (Cont.) Characteristics

1. Type: defined in /usr/include/sys/types.h SOCK_STREAM: connection, sequenced, reliable,

variable-length stream of bytes SOCK_DGRAM: connectionless, unreliable,

fixed length messages

Slide 72

Socket (Cont.) Characteristics (Cont.)

2. Domain: server and client locationAF/PF (Address Family/Protocol Family)

AF_UNIX/PF_UNIX: Server and client are in same machine defined in /usr/include/sys/un.h

AF_INET/PF_INET Server and client are in internet defined in /usr/include/netinet/in.h,

/usr/include/arpa/inet.h, /usr/include/netdb.h

Slide 73

Socket (Cont.) Characteristics (Cont.)

3. Protocols: how socket type is implemented Use default value 0

Slide 74

Server Process (Socket) Steps:

1. Create a socket

2. Name the socket

3. Create a socket queue

4. Accept a client

5. Serving a client

Slide 75

Server Process (Socket) - socket1. Create a socket Syntax: int socket (int domain, int type,

int protocol)) Return file descriptor representing newly created

socket in domain with type and protocol

Example:

serverFd = socket (AF_UNIX, SOCK_STREAM,

DEFAULT_PROTOCOL);

Slide 76

Server Process (Socket) - bind2. Name the socket Syntax: int bind (int fd,

const struct sockaddr* addr, size_t addrlength)

Return 0 to associate unnamed socket (fd) with socket address stored in addr with address structure length addrlength

addr: a pointer to

Slide 77

Server Process (Socket) – bind (Cont)

2. Name the socket (Cont.) addr: if socket in domain

AF_UNIX cast to (sockaddr*) the pointer to structure sockaddr_un

field: sun_family = AF_UNIX field: sun_path = relative or absolute pathname of socket

name AF_INET

cast to (sockaddr*) the pointer to structure sockaddr_in field: sun_family = AF_INET field: sun_port = socket port number field: sun_addr = in_addr structure that holds IP address

Slide 78

Server Process (Socket) – bind (Cont.)

2. Name the socket (Cont.) Example:struct sockaddr_un serverUNIXAddress;struct sockaddr* serverSockAddrPtr;serverSockAddrPtr =

(struct sockaddr*) &serverUNIXAddress;serverLen = sizeof (serverUNIXAddress);serverUNIXAddress.sun_family = AF_UNIX; strcpy (serverUNIXAddress.sun_path, "recipe");unlink ("recipe"); /* Remove file if it already exists */bind (serverFd, serverSockAddrPtr, serverLen);

Slide 79

Server Process (Socket) - listen

3. Create a socket queue Syntax: int listen (int fd, int queuelength)

Specify max queuelength for socket (fd).

Reject client request if queue is full

Example:

listen (serverFd, 5);

Slide 80

Server Process (Socket) - accept4. Accept a client Syntax: int accept (int fd,

struct sockaddr* addr,

int *addrlength returns a file descriptor to communicate with client creates a newly unnamed client socket with the same

attributes as the named server socket fd addr stores client’s IP address similar to the one used

in bind

Slide 81

Server Process (Socket) – accept (Cont.)

4. Accept a client (Cont.) Example:

struct sockaddr_un clientUNIXAddress;

struct sockaddr* serverSockAddrPtr;

struct sockaddr* clientSockAddrPtr;

clientSockAddrPtr =

(struct sockaddr*) &clientUNIXAddress;

clientLen = sizeof (clientUNIXAddress);

clientFd =

accept (serverFd, clientSockAddrPtr, &clientLen);

Slide 82

Server Process (Socket) (Cont.)

5. Serving a client fork a child process to communicate with server

using read() and write() Close communication between server socket and

client socket to free up server to accept new

client’s request

Slide 83

Server Process (Socket) (Cont.)5. Serving a client (Cont.)

Example:while (1) {

clientFd = accept (serverFd, clientSockAddrPtr, &clientLen);if (fork () == 0) {

writeRecipe (clientFd); /* Send the recipe */close (clientFd); /* Close the socket */exit (0); /* Terminate */}

elseclose (clientFd); /* Close the client descriptor

*/}

Slide 84

Client Process (Socket) Steps:

1. Create a unnamed socket

2. Connect to named server socket

Slide 85

Client Process (Socket) - socket1. Create a socket (similar to the one for server) Syntax: int socket (int domain, int type,

int protocol)) Return file descriptor representing newly created

socket in domain with type and protocol

Example:

clientFd = socket (AF_UNIX, SOCK_STREAM,

DEFAULT_PROTOCOL);

Slide 86

Client Process (Socket) - connect2. Connect to named server socket Syntax: int connect (int clientFd,

const struct sockaddr* serveraddr,

size_t addrlength) Return 0 to associate unnamed client socket

(clientFd) with named socket address stored in addr with address structure length addrlength

serveraddr: similar to addr used in bind

Slide 87

Client Process (Socket) – connect (Cont.)

2. Connect to named server socket (Cont.) Example:struct sockaddr_un serverUNIXAddress;struct sockaddr* serverSockAddrPtr;serverSockAddrPtr = (struct sockaddr*) &serverUNIXAddress;serverLen = sizeof (serverUNIXAddress);clientFd = socket (AF_UNIX, SOCK_STREAM,

DEFAULT_PROTOCOL);serverUNIXAddress.sun_family = AF_UNIX; strcpy (serverUNIXAddress.sun_path, "recipe"); do {

result = connect (clientFd, serverSockAddrPtr, serverLen);if (result == -1) sleep (1); /* Wait and then try again */

}while (result == -1);

Slide 88

AF_UNIX Socket Example: IPC in same machine

Compile: gcc –o chef –lsocket chef.c

chef.c (server) Compile: gcc –o cook –lsocket cook.c

cook.c (client) Execute:

chef &

cook

Slide 89

Internet Socket Socket with domain AF_INET

32 bit IP address 16 bit port number

Library functions inet_addr, gethostbyname, inet_ntoa,

bzero(BSD)/memset(System V), htonl/htons/ntohl/ntohs

System calls hethostname

Slide 90

Socket Library – inet_addr Syntax: in_addr_t inet_addr

(const char *ipstring) Return 32 bit IP address in network-byte order)

given an ipstring in a.b.c.d format

Example:

if (isdigit (name[0])) return (inet_addr (name));

Slide 91

Socket Library – gethostbyname Syntax: struct hostent *gethostbyname

(const char *name) Return a pointer to hostent structure by searching

through /etc/hosts file entry with the entry name IP address stored in the field h_addr->s_addr of the

hostent structure

Slide 92

Socket Library – inet_ntoa Syntax: char * inet_ntoa

(struct in_addr address) Return a pointer to a string in a.b.c.d format

by converting an in_addr structure

Slide 93

Socket Library – gethostbyname, inet_ntoa (Cont.)

Example:struct hostent* hostStruct;struct in_addr* hostNode;

char hostName [100];hostStruct = gethostbyname (hostName);if (hostStruct == NULL) return (0); /* Not Found */hostNode = (struct in_addr*) hostStruct->h_addr;printf ("Internet Address = %s\n", inet_ntoa (*hostNode));return (hostNode->s_addr); /* Return IP address */

Slide 94

Socket Library – bzero Syntax: void bzero (void *buffer,

size_t length) Fills buffer with length NULL BSD version

Slide 95

Socket Library – bzero (Cont.) Example:

/* Start by zeroing out the entire address structure */

bzero ((char*)&serverINETAddress,

sizeof(serverINETAddress));

Slide 96

Socket Library –memset Syntax: void memset (void *buffer,

int value, size_t length) Fills buffer with length value System V version

Slide 97

Socket Library – htonl/htons/ntohl/ntohs Syntax: in_addr_t htonl

(in_addr_t host_format_long) in_addr_t ntonl

(in_addr_t net_format_long) in_port_t htons

(in_port_t host_format_short) in_port_t ntons

(in_port_t net_format_short) Coversion between host-format and network-format

Slide 98

Socket Library – htonl/htons/ntohl/ntohs (Cont.)

Example:

serverINETAddress.sin_family = AF_INET;

serverINETAddress.sin_addr.s_addr = inetAddress;

serverINETAddress.sin_port =

htons (DAYTIME_PORT);

Slide 99

Internet Socket – gethostname Syntax: int gethostname (char *name, int

length) Stores hostname in name of length

Example:

gethostname (hostName,100);

Slide 100

Internet Socket (Cont.) Internet server

Similar to AF_UNIX server except the field

sin_addr.s_addr needs to store INADDR_ANY

to accept any incoming client requests

Slide 101

Internet Socket - internet server Example:

struct sockaddr_un serverUNIXAddress;

struct sockaddr_un clientUNIXAddress;

struct sockaddr_in serverINETAddress;

struct sockaddr_in clientINETAddress;

struct sockaddr* serverSockAddrPtr;

struct sockaddr* clientSockAddrPtr;

Slide 102

Internet Socket - internet server (Cont.) Example: (Cont.)if (internet) {

sscanf (name, "%d", &port); /* Get port number */serverLen = sizeof (serverINETAddress);bzero ((char*) &serverINETAddress, serverLen);serverINETAddress.sin_family = AF_INET; /* Domain */serverINETAddress.sin_addr.s_addr =

htonl (INADDR_ANY);serverINETAddress.sin_port = htons (port); /* Port */serverSockAddrPtr = (struct sockaddr*) &serverINETAddress;

}

Slide 103

Internet Socket (Cont.) Internet client

Similar to AF_UNIX client

Example:clientFd = socket (AF_INET, SOCK_STREAM,

DEFAULT_PROTOCOL);do /* Loop until a connection is made with the server */ {

result = connect (clientFd,serverSockAddrPtr,serverLen);if (result == -1) sleep (1); /* Try again in 1 second */

}

Slide 104

Internet Socket (Cont.) Example 1: Internet time

Compile: gcc –o inettime –lsocket –lnsl inettime.c

inettime.c (client) Execute:

inettime

(Enter s, IP address or FQDN: rucs.radford.edu)

Slide 105

Internet Socket (Cont.) Example 2: Internet shell

Compile: gcc –o ish –lsocket –lnsl ish.c

ish.c (server & client) Execute:

ish

Slide 106

Other System Calls Thread Semaphore STREAMS I/O Shared memory

Slide 107

Other Library Calls – Thread Thread:

Multiple threads of control in a single process space light-weight process Shared code, data, stack Defined in /usr/include/pthread.h

Slide 108

Other Library Calls – Thread (Cont.) Thread library functions:

pthread_create/pthread_exit pthread_attr_init/pthread_attr_destroy pthread_attr_setscope/pthread_attr_getscope pthread_join pthread_detach pthread_cancel

Slide 109

Other Library Calls – Thread (Cont.) pthread_create/pthread_exit Syntax: int pthread_create (pthread_t *thread,

const pthread_attr_t *attr,

void * (*startpgm, void*),

void *arg) Create a thread with attribute attr and executing

startpgm using arg

Slide 110

Other Library Calls – Thread (Cont.) pthread_create/pthread_exit (Cont.) Syntax: void pthread_exit (void *status)

Terminate a thread with status

Example:

pthread_exit(0);

Slide 111

Other Library Calls – Thread (Cont.) pthread_create/pthread_exit (Cont.) Example:

#include <pthread.h>void *Simulator(void *arg);pthread_t slave_threads[numThreads];pthread_attr_t pthread_attr;/* Create slave threads */for (i = 1; i<=numThreads;i++) {

if( pthread_create(&slave_threads[i-1], &pthread_attr, Simulator, (void *) ( i ))) {

perror("Error while creating a thread.");exit(3); } }

Slide 112

Other Library Calls – Thread (Cont.) pthread_attr_init/pthread_attr_destroy Syntax: int pthread_attr_init

(pthread_attr_t *attr) Initalize a thread attribute attr with default values

Syntax: int pthread_attr_destroy

(pthread_attr_t *attr) destroy a thread attribute attr

Slide 113

Other Library Calls – Thread (Cont.) pthread_attr_init/pthread_attr_destroy (Cont.) Example:

pthread_attr_init(&pthread_attr);

Slide 114

Other Library Calls – Thread (Cont.) pthread_attr_setscope/pthread_attr_getscope Syntax: int pthread_attr_setscope

(pthread_attr_t *attr,int contentionscope)

Syntax: int pthread_attr_getscope(pthread_attr_t *attr,int contentionscope)

Set or get contentionscope attribute

Slide 115

Other Library Calls – Thread (Cont.) pthread_attr_setscope/pthread_attr_getscope

(Cont.) Example:

pthread_attr_setscope(&pthread_attr,

PTHREAD_SCOPE_SYSTEM);

Slide 116

Other Library Calls – Thread (Cont.) pthread_join Syntax: int pthread_join (pthread_t *thread,

void **status) Wait for another thread to complete with status

Slide 117

Other Library Calls – Thread (Cont.) pthread_detach Syntax: int pthread_detach (pthread_t *thread)

Reclaim thread space after it terminates

Slide 118

Other Library Calls – Thread (Cont.) pthread_cancel Syntax: int pthread_cancel (pthread_t *thread)

cancel thread execution

Slide 119

Other Library Calls – Semaphore Semaphore :

Counter to specify how many concurrent uses of

a resource. If <= 0, then no resource available Binary semaphore: semaphore is binary

Defined in /usr/include/ semaphore.h

Slide 120

Other Library Calls – Semaphore (Cont.)

Semaphore library functions: sem_wait sem_post sem_getvalue

Slide 121

Other Library Calls – Semaphore (Cont.)

sem_wait Syntax: int sem_wait (sem_t *sem)

Lock semophore sem

Slide 122

Other Library Calls – Semaphore (Cont.)

sem_post Syntax: int sem_post (sem_t *sem)

Unlock semophore sem and increment its value

Slide 123

Other Library Calls – Semaphore (Cont.) sem_wait / sem_post (Cont.) Example:

#include <semaphore.h>sem_t useRand; /* generate 20 random number and calculate g(u1,u2,...,u20) */ sem_wait(&useRand);/* Waiting to use random generator */ for( j=0; j < 20; j++) {

seeds[j] = (5*seeds[j]+234) % 49764311;x = seeds[j]/49764311.0;power = power + x; }

sem_post(&useRand); /* Letting others to use generator */

Slide 124

Other Library Calls – Semaphore (Cont.)

sem_getvalue Syntax: int sem_getvalue

(sem_t *sem, int *svalue) Store value of semophore sem to location svalue

Slide 125

Other System Calls – Semaphore System V only

semget(): create an array of semaphore semop(): operate on an array of semaphore semctl(): modify attributes of an array of semaphore

Slide 126

Other System Calls – STREAMS System V only:

has TLI (transport Layer Interface) networking to

STREAMS driver System call

getmsg (): get a message from stream putmsg (): put a message on a stream poll (): poll streams for activity isastream (): test a file desciptor is a stream

Slide 127

Other System Calls – Shared Memory System V only:

If creation of shared memory segment success, it returns a segment ID

System call shmget (): allocate a shared memory segment and return

an ID shmat (): attach a shared memory segment to address

space of calling process shmdt (): detach the segment from address space shmctl (): modify attributes of a shared memory segment

Slide 128

Reference: Chapter 13 of Glass: Unix