16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Interprocess Communication<br />

if ((sockfd = socket ( ... )) < 0)<br />

err_sys("socket error");<br />

if (bind(sockfd, ... ) < 0)<br />

err_sys ("bind error");<br />

if (listen(sockfd, 5) < 0)<br />

err_sys("listen error");<br />

for ( ;; ) { /* concurrent server */<br />

newsockfd = accept (sockfd, ... ); /* blocks */<br />

if (newsockfd < 0)<br />

err_sys ("accept error");<br />

if (fork () = 0) {<br />

close(sockfd); /* child */<br />

doit(newsockfd); /* process request */<br />

exit(0);<br />

}<br />

close(newsockfd); /* parent */<br />

}<br />

OR<br />

for ( ;; ) { /* iterative server */<br />

newsockfd = accept(sockfd, ... ); /* blocks */<br />

if (newsockfd < 0)<br />

err_sys("accept error");<br />

doit(newsockfd); /* process request */<br />

close(newsockfd); /* parent */<br />

}<br />

send, sendto, recv, recvfrom System Calls<br />

#include <br />

#include <br />

int send(int sockfd, char *buff, int nbytes, int flags);<br />

int sendto (int sockfd, char *buff, int nbytes, int flags,<br />

struct sockaddr *to, int addrlen);<br />

int recv(int sockfd, char *buff, int nbytes, int flags);<br />

int recvfrom(int sockfd, char *buff, int nbytes, int flags,<br />

struct sockaddr *from, int *addrlen);<br />

flags MSG_OOB send or receive out of band data<br />

MSG_PEEK<br />

peek at incoming message<br />

MSG_DONROUTE bypass routing<br />

close System Call<br />

int close(int fd);<br />

Byte Ordering Routines<br />

#include <br />

#include <br />

u_long htonl(u_long hostlong); /* host to network */<br />

u_short htons(u_short hostshort);<br />

u_long ntohl(u_long netlong); /* network to host */<br />

u_short ntohs(u_short netshort);<br />

Byte Operations<br />

bcopy(char *src, char *dest, int nbytes);<br />

bzero(char *dest, int nbytes); /* write null bytes */<br />

int bcmp(char * ptr1, char *ptr2, int nbytes);<br />

System V has functions: memcpy, memset, and memcmp<br />

167

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!