Download presentation
Presentation is loading. Please wait.
1
Chapter 12 Advanced Programming: Systems Calls
By C. Shing ITEC Dept Radford University
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
3
System Calls Programmer’s interface to kernel
Capabilities: function returns -1 if failed Error handling: library routine - perror() File management Process management
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()
5
System Calls (Cont.) File management (Cont.) Directory: getdents()
Special (IPC): mknod(), ioctl(), pipe() Sockets: accept(), bind(), connect(), listen(), socke() Internet sockets: gethostbyname(), gethostname(), htonl(), htons(), inet_addr(), inet_ntoa()
6
System Calls (Cont.) Process management:
fork(), exec(), wait(), exit(), chdir(), setuid(), setgid(), getuid(), getgid(), getpid(), getppid() Signals: kill()
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
8
Error Handling – perror (Cont.)
Example: showErrno.c
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
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
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
12
Regular File Management – chown/lchown/fchown
Syntax: int chown (const char *filename, int ownerid, int groupid) int lchown (const char *filename, 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
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
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
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
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
17
Regular File Management – fcntl (Cont.)
Example: myfcntl.c
18
Regular File Management – stat/lstat/fstat
Syntax: int stat (const char *filename, struct stat *buffer) int lstat (const char *filename, 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
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
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
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
22
Regular File Management – stat/lstat/fstat (Cont.)
Example: monitor.c
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
24
Regular File Management - sync
Syntax: void sync (void) Flush all file system buffers to be written to disks
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.
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
27
Directory File Management – getdents/getdirectries (Cont.)
Example: truncate.c count.c
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
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
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
31
Process Management – getpid, getppid
Syntax: pid_t getpid (void) Returns process id Syntax: pid_t getppid (void) Returns parent’s process id
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
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
34
Process Management – fork (Cont.)
Example: myfork.c
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
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
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
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[])
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
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}; execvp (“ls”, cmd};
41
Process Management– execl/execv/execlp/execvp(Cont.)
Example: myexec.c
42
Process Management– execl/execv/execlp/execvp(Cont.)
Example 1: create a background process (process group changed) steps: Create a child process to exec the background process See background.c (background gcc mywait.c)
43
Process Management– execl/execv/execlp/execvp(Cont.)
Example 2: redirect output (ls -l > ls.out) Steps: Open the right hand side of > Duplicate fd from step 1 to stdout and close the fd. In this way stdout will associate with this fd exec the left hand side of > See redirect.c (redirect ls.out ls –l)
44
Process Management – chdir
Syntax: int chdir (const char *dirpath) Set process’ working directory to address of dirpath Example: mychdir.c
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
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
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
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
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.
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
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
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
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
54
Process Management (Signal) – signal (Cont.)
Example: User-supplied handler: handler.c Kernel-supplied signal & Ignore signal: critical.c
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
56
Process Management (Signal) – kill (Cont.)
Example of using signal code: Suspend process kill (pid, SIGSTOP); Resume process kill (pid, SIGCONT);
57
Process Management (Signal) – kill (Cont.)
Example: limit.c process groups of parent and child: pgrp1.c pgrp2.c pgrp3.c
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
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
60
Unnamed Pipe Creation: fd[0] is read end, fd[1] is write end
int fd[2]; pipe(fd);
61
Unnamed Pipe (Cont.) Use // for read process
Close read end of the write process before write // for write process close (fd[0]); write (fd[1], buffer, length); Close write end of the read process before read // for read process close (fd[1]); read (fd[0], buffer, length);
62
Unnamed Pipe (Cont.) // for write process // for read process
if write size no more than pipe size, no pre-empt if pipe read end close, write fails and send SIGPIPE signal to terminate // for read process if read more bytes than pipe has, return actual bytes read if write end open and read an empty pipe, suspend if pipe write end close, read returns 0
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
64
Process Management – pipe (Cont.)
Unix shell: unnamed pipe // for write process Close read end of the write process before write Duplicate write end to stdout Close write end so stdout will be used for write process Exec write process // for read process Close write end of the read process before read Duplicate read end to stdin Close read end so stdin will be used for read process Exec read process Example: connect.c (connect who wc)
65
Named Pipe (FIFO) Creation: use mknod to create a special file
and set right permission mknod (“mypipe”, S_IFIFO, 0); chmod (“mypipe”, 0660);
66
Named Pipe (FIFO) (Cont.)
Use // for read process Delete the pipe unlink (“mypipe”); Create the pipe mknod (“mypipe”, S_IFIFO, 0); chmod (“mypipe”, 0660); Open the pipe for read fd = open (“mypipe”, O_RDONLY); start read process read (fd, buffer, size);
67
Named Pipe (FIFO) (Cont.)
Use (Cont.) // for write process Open the pipe for write fd = open (“mypipe”, O_WRONLY); start write process write (fd, buffer, size);
68
Named Pipe (FIFO) (Cont.)
// for write process if open a named pipe for write, but no 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 process if open a named pipe for read, but read process suspend until a process open for the file to write, unless O_NONBLOCK/O_NDELAY is set (in which open success)
69
Named Pipe (FIFO) (Cont.)
Example: (reader & writer & writer &) reader.c writer.c
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
71
Socket (Cont.) Characteristics
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
72
Socket (Cont.) Characteristics (Cont.)
Domain: server and client location AF/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
73
Socket (Cont.) Characteristics (Cont.)
Protocols: how socket type is implemented Use default value 0
74
Server Process (Socket)
Steps: Create a socket Name the socket Create a socket queue Accept a client Serving a client
75
Server Process (Socket) - socket
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);
76
Server Process (Socket) - bind
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
77
Server Process (Socket) – bind (Cont)
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
78
Server Process (Socket) – bind (Cont.)
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);
79
Server Process (Socket) - listen
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);
80
Server Process (Socket) - accept
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
81
Server Process (Socket) – accept (Cont.)
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);
82
Server Process (Socket) (Cont.)
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
83
Server Process (Socket) (Cont.)
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 */} else close (clientFd); /* Close the client descriptor */ }
84
Client Process (Socket)
Steps: Create a unnamed socket Connect to named server socket
85
Client Process (Socket) - socket
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);
86
Client Process (Socket) - connect
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
87
Client Process (Socket) – connect (Cont.)
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);
88
AF_UNIX Socket Example: IPC in same machine chef.c (server)
Compile: gcc –o chef –lsocket chef.c chef.c (server) Compile: gcc –o cook –lsocket cook.c cook.c (client) Execute: chef & cook
89
Internet Socket Socket with domain AF_INET Library functions
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
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));
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
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
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 */
94
Socket Library – bzero Syntax: void bzero (void *buffer,
size_t length) Fills buffer with length NULL BSD version
95
Socket Library – bzero (Cont.)
Example: /* Start by zeroing out the entire address structure */ bzero ((char*)&serverINETAddress, sizeof(serverINETAddress));
96
Socket Library –memset
Syntax: void memset (void *buffer, int value, size_t length) Fills buffer with length value System V version
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
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);
99
Internet Socket – gethostname
Syntax: int gethostname (char *name, int length) Stores hostname in name of length Example: gethostname (hostName,100);
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
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;
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; }
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 */ }
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)
105
Internet Socket (Cont.)
Example 2: Internet shell Compile: gcc –o ish –lsocket –lnsl ish.c ish.c (server & client) Execute: ish
106
Other System Calls Thread Semaphore STREAMS I/O Shared memory
107
Other Library Calls – Thread
Multiple threads of control in a single process space light-weight process Shared code, data, stack Defined in /usr/include/pthread.h
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
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
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);
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); } }
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 destroy a thread attribute attr
113
Other Library Calls – Thread (Cont.)
pthread_attr_init/pthread_attr_destroy (Cont.) Example: pthread_attr_init(&pthread_attr);
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 Set or get contentionscope attribute
115
Other Library Calls – Thread (Cont.)
pthread_attr_setscope/pthread_attr_getscope (Cont.) Example: pthread_attr_setscope(&pthread_attr, PTHREAD_SCOPE_SYSTEM);
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
117
Other Library Calls – Thread (Cont.)
pthread_detach Syntax: int pthread_detach (pthread_t *thread) Reclaim thread space after it terminates
118
Other Library Calls – Thread (Cont.)
pthread_cancel Syntax: int pthread_cancel (pthread_t *thread) cancel thread execution
119
Other Library Calls – 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
120
Other Library Calls – Semaphore (Cont.)
Semaphore library functions: sem_wait sem_post sem_getvalue
121
Other Library Calls – Semaphore (Cont.)
sem_wait Syntax: int sem_wait (sem_t *sem) Lock semophore sem
122
Other Library Calls – Semaphore (Cont.)
sem_post Syntax: int sem_post (sem_t *sem) Unlock semophore sem and increment its value
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) % ; x = seeds[j]/ ; power = power + x; } sem_post(&useRand); /* Letting others to use generator */
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
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
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
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
128
Reference: Chapter 13 of Glass: Unix
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.