prof. edmundo r. m. madeiracrsenna/cursos/mc823-1s08/mc823-socket-tcp.pdf · read and write...
TRANSCRIPT
Carlos R. SennaProf. Edmundo R. M. Madeira
MC823MC823Laboratório de Laboratório de TeleprocessamentoTeleprocessamento
e Redese RedesPrimeiro Semestre 2008
2Programa da DisciplinaA
pres
enta
ção
• Tecnologias de Comunicação:
1.Sockets
2.RMI
3.Web Services
3Critério de AvaliaçãoA
pres
enta
ção
• Quatro projetos com relatórios de comparação (pesos iguais).
• Todos os projetos devem ter notas superiores ou iguais a 5. Se não, a média final é o menor valor entre 4,9 e a média dos quatro projetos.
4Bibliografia
• Stevens, R. W. “Unix NetworkProgramming – Networking APIs: Sockets and XTI” – Vol. 1, SecondEdition, Prentice-Hall, 1998. • BIMECC 005.43St47u
• Tutoriais sobre RMI e Web Services.
Apr
esen
taçã
o
5Tecnologias de ComunicaçãoM
C823
Sockets
6OutlineSo
cket
s
• Socket basics• TCP sockets• Socket details and options• Socket functions• Concurrent server• Example: Echo Server and Echo Client• Signals and Zumbies• I/O Multiplexing• UDP Sockets
Como programar ?
7Outras InformaçõesM
C823 • [email protected]
• LRC - Laboratório de Redes de Computadores
• 5as. 14:00 – 16:00
• Página do curso
• www.ic.unicamp.br/~crsenna
8BasicsSo
cket
s
Copyright ©2000 The McGraw Hill Companies Leon-Garcia & Widjaja: Communication Networks Fig. 2.20
9BasicsSo
cket
s
• An end-point for a IP network connection• what the application layer “plugs into”• programmer cares about Application
Programming Interface (API)• End point determined by two things:
• Host address: IP address is Network Layer• Port number: is Transport Layer
• Two end-points determine a connection: socket pair• ex: 206.62.226.35,p21 + 198.69.10.2,p1500• ex: 206.62.226.35,p21 + 198.69.10.2,p1499
10PortsSo
cket
s
• Numbers (vary in BSD, Solaris):
• 0-1023 “reserved”, must be root
• 1024 – 49151 (registered with IANA)
• 49152 – 65535 “ephemeral”
• /etc/services:
• ftp 21/tcp
• telnet 23/tcp
• finger 79/tcp
• snmp 161/udpIANA — Internet Assigned Numbers Authority (www.iana.org)
11Sockets and the OSSo
cket
s
• User Socket Operating System(Transport Layer)
• User sees “descriptor”, integer index
• like: FILE *, or file index
• returned by socket() call (more later)
12Sockets and the standardsSo
cket
s
Stevens, W. R., UNIX Network Programming Networking API: Sockets and XTI
13Transport LayerSo
cket
s
• UDP: User Datagram Protocol• no acknowledgements• no retransmissions• out of order, duplicate possible• connectionless
• TCP: Transmission Control Protocol• reliable (in order, all arrive, no duplicates)• flow control• connection• duplex
14Socket DetailsSo
cket
s
Unix Network Programming, W. Richard Stevens, Second Edition, 1998, Prentice Hall, BIMECC 005.43St47u
• Socket address structure (Chap. 3 )• TCP client-server (Chap. 4-5 )• UDP client server (Chap. 8 )• Misc. stuff (Chap. 7 )
• setsockopt(), getsockopt()
15Socket Address Structure
#include <sys/types.h>#include <sys/socket.h>struct in_addr {
/* 32-bit IPv4 addresses */
in_addr_t s_addr; };struct sock_addr_in {unit8_t sin_len; /* length of structure */
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* TCP/UDP Port num */
struct in_addr sin_addr; /* IPv4 address */
char sin_zero[8]; /* unused */
}
Sock
ets
16Tamanhos e LimitaçõesSo
cket
s • Tamanho máximo IPv4: 65535 bytes incluindo cabeçalho• Tamanho máximo IPv6• IPv6: opção Jumbo Payload – 32 bits• MTU mínimo de um enlace para:
• IPv4: 68 bytes; IPv6: 576 bytes• Tamanho mínimo do buffer de remontagem – tamanho mínimo
do datagrama que qualquer implementação deve suportar:• IPv4: 576 bytes
MTU – Maximum Transfer Unit
17TCP Client-ServerSo
cket
s
socket( )
bind( )
listen( )
accept( )
socket( )
connect( )
write( )
read( )
write( )
read( )
close( )
Blocks until conection
from client
Process request
read( )
close( )
TCP Server
TCP Client
Connection establishment
(TCP) three-way handshake
data (request)
data (reply)
End-of-file notification
well-known
port
18socket FunctionSo
cket
s int socket(int family, int type, int protocol);Create a socket, giving access to transport layer service.
• family is one of• AF_INET (IPv4), AF_INET6 (IPv6), AF_LOCAL (local Unix),• AF_ROUTE (access to routing tables), AF_KEY (new, for
encryption)
• type is one of• SOCK_STREAM (TCP), SOCK_DGRAM (UDP)• SOCK_RAW (for special IP packets, PING, etc. Must be root)
• protocol is 0 (used for some raw socket options)• upon success returns socket descriptor
• like file descriptor => -1 if failure
Example:if (( sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
err_sys (“socket call error”);
19socket OptionsSo
cket
s • Many socket( ) options• Set/lookup using
• setsockopt(), getsockopt()• Examples:
• SO_LINGER• SO_RCVBUF, SO_SNDBUF (modify buffer sizes)• SO_RCVLOWAT, SO_SNDLOWAT• SO_RCVTIMEO, SO_SNDTIMEO (Timeouts)• TCP_KEEPALIVE (idle time before close (2 hours, default))• TCP_MAXRT (set timeout value)• TCP_NODELAY (disable Nagle Algorithm)
• See man pages for details• man socket on any Unix machine
20connect FunctionSo
cket
s int connect( int sockfd, const struct sockaddr *servaddr,
socklen_t addrlen );Connect to server.
• sockfd is socket descriptor from socket()• servaddr is a pointer to a structure with:
• Server port number and IP address• must be specified (unlike bind())
• addrlen is length of structure• client doesn’t need bind()
• OS will pick ephemeral port• returns socket descriptor if ok, -1 on error
Example: (BG-14)
if (connect (sockfd, (struct sockaddr *) &servaddr, sizeof (servaddr)) != 0)err_sys(“connect call error”);
21bind FunctionSo
cket
s int bind( int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);Assign a local protocol address (“name”) to a socket.
• sockfd is socket descriptor from socket()• myaddr is a pointer to address struct with:
• port number and IP address• addrlen is length of structure• returns 0 if ok, -1 on error
• EADDRINUSE (“Address already in use”)
Example: (BG-12)
if (bind (sd, (struct sockaddr *) &servaddr, sizeof (servaddr)) != 0)errsys (“bind call error”);
22listen FunctionSo
cket
s int listen(int sockfd, int backlog);Announce willingness to accept connections, give queue size, change
socket state for TCP server.
• sockfd is socket descriptor from socket()• backlog is maximum number of incomplete connections
• historically 5• rarely above 15 on a even moderate web server!
• Sockets default to active (for client)
Example:if (listen (sd, 2) != 0)
errsys (“listen call error”);
23listen FunctionSo
cket
s
RTT – Round Trip Time
24accept FunctionSo
cket
s int accept( int sockfd, struct sockaddr cliaddr,socklen_t *addrlen );
Return next completed connection.
• sockfd is socket descriptor from socket()• cliaddr and addrlen return protocol address from client• returns brand new descriptor, created by OS• if used with fork(), can create concurrent server (more
later)
Example:sfd = accept (s, NULL, NULL);if (sfd == -1) err_sys (“accept error”);
25close FunctionSo
cket
s int close(int sockfd);Close socket for use.
• sockfd is socket descriptor from socket()• closes socket for reading/writing
• returns (doesn’t block)• attempts to send any unsent data• -1 if error
26read and write FunctionsSo
cket
s • Pode ler/escrever menos do que necessita devido ao tamanhorestrito do buffer.
• É necessário chamar a função novamente.• Somente o write é nonblocking
• Tamanho máximo IPv4: 65535 bytes incluindo cabeçalho• Tamanho máximo IPv6• IPv6: opção Jumbo Payload – 32 bits• MTU mínimo de um enlace para:
• IPv4: 68 bytes; IPv6: 576 bytes• Tamanho mínimo do buffer de remontagem – tamanho mínimo
do datagrama que qualquer implementação deve suportar:• IPv4: 576 bytes
MTU – Maximum Transfer Unit
27write FunctionSo
cket
s
Aplicação
TCP
IP
Fila saídaEnlace
Buffer da aplicação (qualquer tamanho)
write
Buffer de envio do socket (SO_SNDBUF)
Processo do usuário
Kernel
Segmentos TCP do tamanho do MSSMSS normalmente ≤ MTU – 40 (IPv4) ou MTU – 60 (IPv6)
Pacotes IPv4 ou IPv6 do tamanho da MTU
• Kernel copia dados do buffer da aplicação para buffer do socket.• Se não há espaço, o processo é bloqueado até a transferência do
último byte.
Fragmentação e remontagem do IP
28write Function (lib/writen.c)So
cket
s 1 #include "unp.h" 2 ssize_t /* Write "n" bytes to a descriptor. */3 writen(int fd, const void *vptr, size_t n)4 {5 size_t nleft; 6 ssize_t nwritten; 7 const char *ptr; 8 ptr = vptr; 9 nleft = n; 10 while (nleft > 0) { 11 if ( (nwritten = write(fd, ptr, nleft)) <= 0) { 12 if (nwritten < 0 && errno == EINTR)13 nwritten = 0; /* and call write() again */14 else15 return (-1); /* error */16 } 17 nleft -= nwritten; 18 ptr += nwritten; 19 } 20 return (n); 21 }
29read Function (lib/readn.c)So
cket
s 1 #include "unp.h" 2 ssize_t /* Write "n" bytes to a descriptor. */3 readn(int fd, void *vptr, size_t n)4 {5 size_t nleft; 6 ssize_t nread; 7 char *ptr; 8 ptr = vptr; 9 nleft = n; 10 while (nleft > 0) { 11 if ( (nread = read(fd, ptr, nleft)) < 0) { 12 if (errno == EINTR) 13 nread = 0; /* and call read() again */14 else15 return (-1); 16 } else if (nread == 0) 17 break; /* EOF */18 nleft -= nread; 19 ptr += nread; 20 } 21 return (n - nleft); /* return >= 0 */22 }
30Sending and ReceivingSo
cket
s int recv(int sockfd, void *buff, size_t mbytes, int flags);int send(int sockfd, void *buff, size_t mbytes, int flags);
• Same as read() and write() but for flags
• flags for I/O functions (see man pages)• MSG_DONTWAIT (this send non-blocking)• MSG_OOB (out of band data, 1 byte sent ahead)• MSG_PEEK • MSG_WAITALL (don’t give me less than max)• MSG_DONTROUTE (bypass routing table)
31Servidor ConcorrenteSo
cket
s-
TCP • Após accept e fork, o processo filho executa no
CONNFD e o pai continua a escutar no LISTENFD.
• close decrementa contador de referências.
• FYN é enviado somente quando contador de referências possui valor zero.
32Servidor Concorrente – forkSo
cket
s-
TCP • fork executa uma cópia idêntica do processo.
• Retorna o identificador do processo filho ao pai(process ID) e o valor 0 (process ID) ao filho.
• Os descritores abertos antes do fork sãocompartilhados com os filhos.
• o “connected socked” após um accept seguido de fork é compartilhado com o filho.
# include <unistd.h>pid_t fork(void);
Returns: 0 in child, process ID of child in parent, -1 on error
33Servidor Concorrente – execTC
P • A função exec executa outro programa.
Sock
ets
- #include <unistd.h>
int execl ( const char *pathname, const char *arg0,... /* (char *) 0 */ );int execv ( const char *pathname, char *const argv[ ] );int execle ( const char *pathname, const char *arg0, ...
/* (char *) 0, char *const envp[ ] */ );int execve ( const char *pathname, char *const argv[ ],
char *const envp[ ] );int execlp ( const char *filename, const char *arg0, ... /* (char *) 0 */ );int execvp ( const char *filename, char *const argv[ ] );
All six return: -1 on error, no return on success
34Servidor ConcorrenteSo
cket
s-
TCP pid_t pid;
int listenfd, connfd; /* fill in sockaddr_in{ } with server's well-known port */listenfd = socket( ... ); bind(listenfd, ... ); listen(listenfd, LISTENQ);
for ( ; ; ) { connfd = accept (listenfd, ... ); /* probably blocks */
if( (pid = fork() ) == 0) { close(listenfd); /* child closes listening socket */doit(connfd); /* process the request */close(connfd); /* done with this client */exit(0); /* child terminates */
}
close(connfd); /* parent closes connected socket */}
35Servidor ConcorrenteSo
cket
s-
TCP Client Server
1 connect( ) listenfdconnectionrequest
connect( ) listenfd
connfd
connection2
connectionconnect( ) listenfd
connfdServer
(parent)
fork3listenfd
connfdServer
(child)
connect( )connection
listenfd Server
(parent)
4Server
(child)connfdStevens Vol. 1 Fig. 4.14 a 4.17
36Servidor Concorrente - ExemploSo
cket
s-
TCP • Questões: o que acontece...
• Quando o cliente e o servidor iniciam?• Se o servidor “terminar” antes do cliente finalizar a sessão?
• Servidor Echo
• Cliente Echo
37Servidor Echo (main)So
cket
s-
TCP 1 #include "unp.h"
2 int 3 main(int argc, char **argv) 4 {5 int listenfd, connfd; 6 pid_t childpid; 7 socklen_t clilen; 8 struct sockaddr_in cliaddr, servaddr; 9 listenfd = Socket (AF_INET, SOCK_STREAM, 0); 10 bzero(&servaddr, sizeof(servaddr)); 11 servaddr.sin_family = AF_INET; 12 servaddr.sin_addr.s_addr = htonl (INADDR_ANY); 13 servaddr.sin_port = htons (SERV_PORT); 14 Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); 15 Listen(listenfd, LISTENQ); 16 for ( ; ; ) { 17 clilen = sizeof(cliaddr); 18 connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); 19 if ( (childpid = Fork()) == 0) { /* child process */20 Close(listenfd); /* close listening socket */21 str_echo(connfd); /* process the request */22 exit (0);23 } 24 Close(connfd); /* parent closes connected socket */25 } 26 }
Stevens Vol. 1 Fig. 5.2 TCP echo server
38Servidor Echo (str_echo)So
cket
s-
TCP 1 #include "unp.h"
23 void str_echo(int sockfd)4 {5 ssize_t n; 6 char buf[MAXLINE];
7 again: 8 while ( (n = read(sockfd, buf, MAXLINE)) > 0) 9 writen(sockfd, buf, n); 10 if (n < 0 && errno == EINTR) 11 goto again; 12 else if (n < 0) 13 err_sys("str_echo: read error"); 14 }
39Cliente Echo (main)So
cket
s-
TCP 1 #include "unp.h"
23 int main(int argc, char **argv)4 {5 int sockfd; 6 struct sockaddr_in servaddr; 7 if (argc != 2) 8 err_quit("usage: tcpcli <IPaddress>"); 9 sockfd = Socket(AF_INET, SOCK_STREAM, 0); 10 bzero(&servaddr, sizeof(servaddr)); 11 servaddr.sin_family = AF_INET; 12 servaddr.sin_port = htons(SERV_PORT); 13 Inet_pton(AF_INET, argv[1], &servaddr.sin_addr); 14 Connect(sockfd, (SA *) &servaddr, sizeof(servaddr)); 15 str_cli(stdin, sockfd); /* do it all */16 exit(0); 17 }
Stevens Vol. 1 Fig. 5.4 TCP echo client
40Cliente Echo (str_cli)So
cket
s-
TCP 1 #include "unp.h"
23 str_cli(FILE *fp, int sockfd) 4 { 5 char sendline[MAXLINE], recvline[MAXLINE]; 6 while (Fgets(sendline, MAXLINE, fp) != NULL) { 7 Writen(sockfd, sendline, strlen (sendline)); 8 if (Readline(sockfd, recvline, MAXLINE) == 0) 9 rr_quit("str_cli: server terminated prematurely"); 10 Fputs(recvline, stdout); 11 }12 }
Stevens Vol. 1 Fig. 5.5 str_cli function: client processing loop
41Netstat (início normal)So
cket
s-
TCP linux % tcpserv01 &
[1] 17870
linux % netstat -a
Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address Statetcp 0 0 *:9877 *:* LISTEN
linux % tcpcli01 127.0.0.1 linux % netstat -a
Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address Statetcp 0 0 local host:9877 localhost:42758 ESTABLISHED tcp 0 0 local host:42758 localhost:9877 ESTABLISHEDtcp 0 0 *:9877 *:* LISTEN
linux % ps -t pts/6 -o pid,ppid,tty,stat,args,wchan
PID PPID TT STAT COMMAND WCHAN 22038 22036 pts/6 S -bash wait417870 22038 pts/6 S ./tcpserv01 wait_for_connect19315 17870 pts/6 S ./tcpserv01 tcp_data_wait19314 22038 pts/6 S ./tcpcli01 127.0 read_chan
42Netstat (finalização normal)So
cket
s-
TCP linux % netstat -a | grep 9877
tcp 0 0 *:9877 *:* LISTEN tcp 0 0 localhost:42758 localhost:9877 TIME_WAIT
linux % ps -t pts/6 -o pid,ppid,tty,stat,args,wchanPID PPID TT STAT COMMAND WCHAN 22038 22036 pts/6 S -bash read_chan17870 22038 pts/6 S ./tcpserv01 wait_for_connect19315 17870 pts/6 Z [tcpserv01 <defu do_exit
43Finalização NormalSo
cket
s-
TCP • Ao digitar EOF, fget retorna um ponteiro nulo e a
função str_cli retorna;• O cliente executa exit;• Descriptors no cliente são fechados e um FYN é
enviado ao servidor. Servidor no estado CLOSE_WAITe cliente FIN_WAIT-2;
• O filho servidor estava bloqueado em readline(str_echo) e retorna para main servidor. Filho servidor termina executando exit;
• Todos os descritores do filho servidor são fechados, um FIN do servidor é enviado e um ACK do cliente;
• Conexão terminada; e• Sinal SIGCHLD é enviado.
44signal FunctionSo
cket
s-
TCP Sigfunc *signal(int signo, Sigfunc *func);
• signo is a signal number.• *func is a pointer to a signal handling function, as well as the
return value from the function.
• A signal is a notification to a process that ana event has ocurred.• Are sometimes called software interrupts.• Usually occur asynchronously.• Signals can be sent:
• By one process to another process (or to itself), or• By the Kernel to a process.
45signal FunctionSo
cket
s-
TCP 1 #include "unp.h"
23 Sigfunc *signal (int signo, Sigfunc *func)4 {5 struct sigaction act, oact; 6 act.sa_handler = func; 7 sigemptyset (&act.sa_mask); 8 act.sa_flags = 0; 9 if (signo == SIGALRM) { 10 #ifdef SA_INTERRUPT11 act.sa_flags |= SA_INTERRUPT; /* SunOS 4.x */ 12 #endif13 } else { 14 #ifdef SA_RESTART15 act.sa_flags |= SA_RESTART; /* SVR4, 4.4BSD */ 16 #endif17 } 18 if (sigaction (signo, &act, &oact) < 0) 19 return (SIG_ERR); 20 return (oact.sa_handler); 21 }
Stevens Vol. 1 Fig. 5.6 signal function
46Handling SIGCHLD Signals and ZombiesSo
cket
s-
TCP • The purpose of the zombies state is to maintain information
about the child for the parent to fetch at some later time.• The information includes:
• The process ID of the child;• Its termination status, and• Information on the resource utilization of the child (CPU
Time, memory, etc).• If a process terminates, and the process has children in the
zombie state, the parent process ID of all the zombie childrenis set to 1 (the init process), which will inherit the children andclean them up.
• Whenever we fork children, we must wait for them to preventthem from becoming zombies.
47Handling SIGCHLD Signals and ZombiesSo
cket
s-
TCP Signal (SIGCHLD, sig_chld);
...1 #include “unp.h”23 void sig_chld( int signo )4 {5 pid_t pid;6 int stat;7 pid = wait(&stat);8 printf(“child %d terminated\n”, pid);9 return;10 }
48wait and waitpid Functions-
TCP #include <sys/wait.h>
pid_t wait (int *statloc);pid_t waitpid (pid_t pid, int *statloc, int options);
Both return: process ID if OK, 0 or–1 on error
Sock
ets
Stevens Vol. 1 Fig. 5.10
Client terminates, closing all five connections, terminating all five children.
Server
parent
Server
child #1
Server
child #2
Server
child #3
Server
child #4
Server
child #5
4 3 2 1 0
client exit
FINFINFIN
FIN
FIN
SIGCHLD
SIGCHLD
SIGCHLD
SIGCHLD
SIGCHLD
49wait and waitpid Functions-
TCP • waitpid fetching the status of any of our children that have
terminated.• WNOHANG option specify waitpid not to block.
Sock
ets
Stevens Vol. 1 Fig. 5.11
1 #include "unp.h" 23 void sig_chld(int signo)4 {5 pid_t pid; 6 int stat; 7 while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) 8 printf("child %d terminated\n", pid); 9 return; 10 }
50TCP server that handles na error of EINTRSo
cket
s-
TCP
Stevens Vol. 1 Fig. 5.11
1 #include "unp.h"3 int main(int argc, char **argv)4 { 5 int listenfd, connfd; 6 pid_t childpid; 7 socklen_t clilen; 8 struct sockaddr_in cliaddr, servaddr; 9 void sig_chld(int); 10 listenfd = Socket (AF_INET, SOCK_STREAM, 0); 11 bzero (&servaddr, sizeof(servaddr)); 12 servaddr.sin_family = AF_INET; 13 servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 14 servaddr.sin_port = htons(SERV_PORT); 15 Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); 16 Listen(listenfd, LISTENQ); 17 Signal (SIGCHLD, sig_chld); /* must call waitpid() */18 for ( ; ; ) { 19 clilen = sizeof(cliaddr); 20 if ( (connfd = accept (listenfd, (SA *) &cliaddr, &clilen)) < 0) { 21 if (errno == EINTR) 22 continue; /* back to for() */23 else24 err_sys("accept error"); 25 } 26 if ( (childpid = Fork()) == 0) { /* child process */ 27 Close(listenfd); /* close listening socket */28 str_echo(connfd); /* process the request */29 exit(0); 30 } 31 Close (connfd); /*parent closes connected socket*/32 } 33 }
51Tecnologias de ComunicaçãoM
C823
Sockets
Multiplexação de E/S
52IntroduçãoM
ulti
plex
ação
de E
/S • Capacidade de avisar Núcleo que se deseja ser notificado quando condições de E/S estejam válidas.• Ex: dados para leitura estão disponíveis.
• Funções relacionadas:• select• poll• shutdown
53Quando usarM
ulti
plex
ação
de E
/S • Quando cliente está manipulando vários descritores.• Ex: descritor do socket é de entrada interativa.
• Quando o cliente manipula vários sockets ao mesmo tempo.
• Quando TCP manipula listening sockets e outros sockets conectados
• Quando o servidor trabalha com TCP e com UDP simultaneamente.
• Quando o servidor manipula vários protocolos e serviços simultaneamente.
54Tipos e OperaçõesM
ulti
plex
ação
de E
/S • Tipos:• E/S bloqueante;• E/S não bloqueante ;• Multiplexação de E/S;• E/S orientada a sinal; e• E/S assíncrona.
• Operações em duas fases:• Espera para dados estarem disponíveis e• Cópia dos dados do Kernel para o processo.
55ModeloM
ulti
plex
ação
de E
/S
Stevens Vol. 1 Fig. 6.3
56select FunctionM
ulti
plex
ação
de E
/S #include <sys/select.h>#include <sys/time.h>
struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */
};
int select ( int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, const struct timeval *timeout);
Return: positive count of ready descriptors, 0 on timeout and –1 on error.
57select FunctionM
ulti
plex
ação
de E
/S • Instrui o núcleo para acordar o processo quando:• Um conjunto de eventos ocorrer ou • Um certo intervalo de tempo tiver ocorrido.
• Pode especificar o descritor:• Reading, writing ou exception.
• Três possibilidades de espera:• Espera até condição ser verdadeira – null pointer;• Espera por um valor máximo de intervalo; e• Não espera. Retorna após verificar os descritores (polling).
• Os valores de temporização em timeout devem ser zero.
58poll FunctionM
ulti
plex
ação
de E
/S #include <poll.h>
struct pollfd { int fd; /* descriptor to check */ short events; /* events of interest on fd */ short revents; /* events that occurred on fd */
};
int poll ( struct pollfd *fdarray, unsigned long nfds, int timeout);
Return: -1 if an error occurred, 0 if no descriptors are ready before the timer
expires,Otherwise it is the number of descriptors that have anonzero revents member.
59shutdown FunctionM
ulti
plex
ação
de E
/S #include <sys/socket.h>
int shutdown(int sockfd, int howto);
Return: 0 if OK or -1 on error.
Argumento howto:
• SHUT_RD – fecha para leitura (read-halt).Conteúdo do buffer e futuras recepções são descartadas.
• SHUT_WR – qualquer dado no buffer de escrita será enviado. Não pode mais escrever.
• SHUT_RDWR – efeito de fazer SHUT_WR após o SHUT_RD.
60shutdown FunctionM
ulti
plex
ação
Stevens Vol. 1 Fig. 6.12
de E
/S
61Tecnologias de ComunicaçãoM
C823
Sockets
UDP