Chinaunix首页 | 论坛 | 博客
  • 博客访问: 447168
  • 博文数量: 138
  • 博客积分: 4114
  • 博客等级: 上校
  • 技术积分: 1341
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-14 20:41
文章分类

全部博文(138)

文章存档

2014年(1)

2013年(2)

2012年(78)

2011年(13)

2010年(34)

2009年(10)

我的朋友

分类: LINUX

2012-04-17 11:36:04

Excerpt from

This chapter covers the following topics:

This chapter is adapted with permission from Stuart Sechrest's An Introductory Socket Communication Tutorial. In this chapter, we look at a few simple example programs that show how to use pipes and socketpairs and how to do datagram and stream communication via sockets.

The example programs show different ways of establishing channels of communication and how the data is actually transferred. These programs have been kept as simple as possible so you can use them as models.

You can find the source for the examples in the /usr/demo/src/socket directory.

The Berkeley UNIX 4.2BSD release introduced new facilities for interprocess communication (IPC) and networking. The basic idea behind these facilities (i.e. sockets) was to integrate them with file-descriptor-based I/O. The main reason for this is that all processes already use file descriptors to read and write data to files.

Typically, a process inherits its file descriptors from its parent. By using the new IPC interface to create file descriptors that represent sockets, parent processes can set up their children's file descriptors so that the children can communicate with other processes, even across the network. Although sockets aren't restricted to being set up by the parent process, this is a very powerful outcome of their design.

Previously, signals and pipes provided the principal mechanisms by which IPC was achieved. However, signals are of limited value since they can transmit only a signal type. And while pipes are more effective than signals — they allow file-descriptor-based I/O in a single direction between two process — both ends of the pipe must be set up by a common ancestor. Furthermore, in their initial implementations, pipes were limited to communication within a single computer.

The new uses of file descriptors have affected what the terms “read” and “write” mean. Originally these terms were fairly simple: when you wrote something, it was delivered; when you read something, you were blocked until the data arrived.

But the new IPC has given rise to other interpretations of these terms. You can now write without full assurance of delivery, and you can check later to catch occasional failures. Messages can be kept as discrete units or merged into a stream. You can ask to read, but insist on not waiting if nothing is immediately available.

Pipes are a unidirectional IPC mechanism, with one end of a pipe opened for reading and the other end opened for writing.

To illustrate a common use for pipes, let's look at the shell. When you enter the following command:

ls | more

the shell connects the standard output of ls to the standard input of more via a pipe. Data written into one end of the pipe by ls can be read from the other end by more.

Both the ls and more commands run without knowing they're connected through a pipe. They simply read from file descriptor 0 (standard input) and write to file descriptor 1 (standard output).

In the following example program, the parent creates a pipe for communication between its child and itself. The parent calls the pipe() function, which creates a pipe and places the file descriptors for the two ends of the pipe into the file-descriptor array (which we called sockets).

The file descriptor that's returned in the low word of the array, sockets[0], is open for reading only, while the file descriptor in the high end, sockets[1], is open for writing only.

The name sockets for the file-descriptor array is unnecessary. Nevertheless, as our discussion progresses, the file descriptors in this array will eventually represent sockets.


点击(此处)折叠或打开

  1. tut1.c

  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>

  5. #define DATA "Bright star, would I were steadfast as thou..."

  6. /*
  7.  * This program creates a pipe, then forks.
  8.  * The child communicates to the parent over the pipe.
  9.  * Notice that a pipe is a one-way communications device.
  10.  * I can write to the output socket (sockets[1], the second
  11.  * socket of the array returned by pipe()) and read from the
  12.  * input socket (sockets[0]), but not vice versa.
  13.  */

  14. main()
  15. {
  16.         int sockets[2], child;

  17.         /* Create a pipe */
  18.         if (pipe(sockets) < 0) {
  19.                 perror("opening stream socket pair");
  20.                 exit(10);
  21.         }

  22.         if ((child = fork()) == -1)
  23.                 perror("fork");
  24.         else if (child) {
  25.                 char buf[1024];

  26.            /* This is still the parent. */
  27.            /* It reads the child's message. */

  28.                 close(sockets[1]);
  29.                 if (read(sockets[0], buf, sizeof(buf)) < 0)
  30.                         perror("reading message");
  31.                 printf("-->%s\n", buf);
  32.                 close(sockets[0]);
  33.         } else {

  34.            /* This is the child. */
  35.            /* It writes a message to its parent. */

  36.                 close(sockets[0]);
  37.                 if (write(sockets[1], DATA, sizeof(DATA)) < 0)
  38.                         perror("writing message");
  39.                 close(sockets[1]);
  40.         }
  41. }

If the parent and child need two-way communication via pipes, the parent creates two pipes, one for use in each direction. (In accordance with their plans, both parent and child in the above example close the socket they won't use. Unused descriptors don't have to be closed, but it's good practice.)

Note that a pipe is a stream-communication mechanism; that is, all messages sent through the pipe are placed in order and are reliably delivered.

When the reader asks for a certain number of bytes from this stream, all the available bytes are returned. This may be less than what's requested. Note that these bytes may have come from the same call to write() or from several concatenated calls to write().

You can view socketpairs as an extension of pipes. Where a pipe can be viewed as a pair of connected sockets for one-way stream communication, a socketpair can be viewed as a pair of connected sockets for two-way stream communication.

To obtain a pair of connected sockets for two-way stream communication, you call the socketpair() function. This function takes as arguments a domain, a style of communication, and a protocol; these arguments are shown in the following example.

Socketpairs have been implemented for only one domain, called the UNIX domain. (Briefly, a domain is a space of names that may be bound to sockets and that implies certain other conventions; we'll look at both domains and protocols in detail in the next section.)

The constants AF_UNIX and SOCK_STREAM are defined in sys/socket.h, which in turn requires the file sys/types.h for some of its definitions.


点击(此处)折叠或打开

  1. tut2.c

  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>

  7. #define DATA1 "In Xanadu, did Kublai Khan..."
  8. #define DATA2 "A stately pleasure dome decree..."

  9. /*
  10.  * This program creates a pair of connected sockets,
  11.  * then forks and communicates over them. While this
  12.  * is very similar to communication with pipes, socketpairs
  13.  * are two-way communications objects. Therefore, I can
  14.  * send messages in both directions.
  15.  */

  16. main()
  17. {
  18.         int sockets[2], child;
  19.         char buf[1024];

  20.         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
  21.                 perror("opening stream socket pair");
  22.                 exit(1);
  23.         }

  24.         if ((child = fork()) == -1)
  25.                 perror("fork");
  26.         else if (child) { /* This is the parent. */
  27.                 close(sockets[0]);
  28.                 if (read(sockets[1], buf, sizeof(buf)) < 0)
  29.                         perror("reading stream message");
  30.                 printf("-->%s\n", buf);
  31.                 if (write(sockets[1], DATA2, sizeof(DATA2)) < 0)
  32.                         perror("writing stream message");
  33.                 close(sockets[1]);
  34.         } else { /* This is the child. */
  35.                 close(sockets[1]);
  36.                 if (write(sockets[0], DATA1, sizeof(DATA1)) < 0)
  37.                         perror("writing stream message");
  38.                 if (read(sockets[0], buf, sizeof(buf)) < 0)
  39.                         perror("reading stream message");
  40.                 printf("-->%s\n", buf);
  41.                 close(sockets[0]);
  42.         }
  43. }

Pipes and socketpairs are limited to communication between processes with a common ancestor. Whenever you have processes that have no common ancestor and that may be running on different computers, each process has to create its own sockets and then send messages through them.

Sockets created by different programs use names to refer to one another. To be used, these names generally must be translated into addresses. The space that an address is drawn from is referred to as a domain.

There are several domains for sockets; you're most likely to encounter these two:

  • UNIX domain (or AF_UNIX, for Address Format UNIX)
  • internet domain (or AF_INET)

With the exception of socketpair(), UNIX domain sockets aren't supported in QNX. But QNX does support internet domain sockets.

The internet domain is the UNIX implementation of the DARPA internet standard protocols IP, TCP, and UDP. Addresses in the internet domain consist of a machine network address and an identifying number, called a port. Internet domain names allow communication between machines.

Two “types” or “styles” of communication are supported:

  • stream
  • datagram

Depending on the implementation, different protocols are used to achieve the required style of communication.

Stream communication, which takes place across a connection between two sockets, is reliable and error-free. And as with pipes, there are no message boundaries.

Reading from a stream may get data sent by one or more calls to the write() function. In some cases, the data returned from a read() call is only part of the data that was written (e.g. there isn't enough room for the entire message, or not all the data from a large message has been transferred).

The protocol implementing stream communication will retransmit messages that are received with errors. It will also return error conditions if a process tries to send a message after the connection has been broken.

Datagram communication doesn't use connections; each datagram message is addressed individually. If the address is valid, the datagram is usually received, but this isn't guaranteed. Often datagrams are used for requests that require a response from the recipient. If no response arrives in a reasonable amount of time, the request is repeated. The individual datagrams are kept separate when they're read (i.e. message boundaries are preserved).

The difference in performance between stream and datagram communication is generally less important than the difference in semantics. The performance gain you might find in using datagrams must be weighed against the increased complexity of the program, which must now concern itself with lost or out-of-order messages. If you can ignore lost messages, then you may wish to consider the quantity of traffic; if you'll use the connection frequently, the expense of setting up a connection for stream communication is justified.

A protocol is a set of rules, data formats, and conventions that regulates the transfer of data between communicating processes. In general, there's one protocol for each socket type (stream, datagram, etc.) within each domain. The code that implements a protocol:

  • keeps track of the names bound to sockets
  • sets up connections
  • transfers data between sockets, perhaps sending the data across a network.

Several protocols can implement the same style of communication within a particular domain, each differing only in low-level details. Though you can select which protocol should be used, it's usually sufficient to request the default protocol. We've followed this practice in all of the example programs.

When creating a socket, you must specify its domain, style, and protocol. The sample code on the following pages demonstrates this requirement.

When a message must be sent between machines, it's sent to the protocol handler on the destination machine, which interprets the address and determines which socket the message should be delivered to. The socket is bound to a port, which is a delivery slot managed by the functions that implement a particular protocol. Note that if several protocols are active on the same machine, they won't communicate with one another.

The protocol for a socket is chosen when the socket is created. The local machine address for a socket can be any valid IP address of the machine — if the machine has more than one — or it can be the wildcard value INADDR_ANY (this wildcard value is used in the following example program).

If a computer has several IP addresses, it's likely that messages sent to any of the addresses should be deliverable to a socket. This will be the case if the wildcard value has been chosen. Note that even if the wildcard value is chosen, a program sending messages to the named socket must specify a valid network address — the program can be willing to receive from “anywhere,” but can't send a message “anywhere.”

In the example program below, the destination hostname is given as a command-line argument. To determine a network address it can send the message to, the program looks up the host address by the call to gethostbyname(). The returned structure includes the host's network address, which is copied into the structure that specifies the message's destination.

You can think of the port number as the number of a mailbox into which the protocol places your messages. Certain daemons offering advertised services have reserved or “well-known” port numbers that fall in the range from 1 to 1023. Higher numbers are available to general users. See /etc/services and getservbyname().

Only servers need to ask for a particular number. The system will assign an unused port number when an address is bound to a socket. This may happen when an explicit bind()call is made with a port number of 0, or when a connect() or a send() is performed on an unbound socket. Note that port numbers aren't automatically reported back to the user. After calling bind() with a port value of 0, an application may call getsockname() to discover what port the bind() function actually assigned.

Let's now look at two programs that create sockets separately. The structure of internet domain addresses is defined in the file netinet/in.h.


点击(此处)折叠或打开

  1. tut3.c

  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <stdlib.h>

  8. main()
  9. {
  10.         int sock, length;
  11.         struct sockaddr_in name;
  12.         char buf[1024];

  13.         /* Create socket from which to read. */
  14.         sock = socket(AF_INET, SOCK_DGRAM, 0);
  15.         if (sock < 0) {
  16.                 perror("opening datagram socket");
  17.                 exit(1);
  18.         }

  19.         /* Create name with wildcards. */
  20.         name.sin_family = AF_INET;
  21.         name.sin_addr.s_addr = INADDR_ANY;
  22.         name.sin_port = 0;
  23.         if (bind(sock, &name, sizeof(name))) {
  24.                 perror("binding datagram socket");
  25.                 exit(1);
  26.         }
  27.         
  28.         /* Find assigned port value and print it out. */
  29.         length = sizeof(name);
  30.         if (getsockname(sock, &name, &length)) {
  31.                 perror("getting socket name");
  32.                 exit(1);
  33.         }
  34.         printf("Socket has port #%d\n", ntohs(name.sin_port));
  35.         
  36.         /* Read from the socket */
  37.         if (read(sock, buf, sizeof(buf)) < 0)
  38.                 perror("receiving datagram packet");
  39.         printf("-->%s\n", buf);
  40.         close(sock);
  41. }

In the following example, an internet domain datagram is sent to a receiver whose name is obtained from command-line arguments. The form of the command line is:

点击(此处)折叠或打开

  1. tut4 hostname portnumber
  2. tut4.c

  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <netinet/in.h>
  6. #include <netdb.h>
  7. #include <stdio.h>

  8. #define DATA "The sea is calm tonight, the tide is full..."

  9. main(argc, argv)
  10.         int argc;
  11.         char *argv[];
  12. {
  13.         int sock;
  14.         struct sockaddr_in name;
  15.         struct hostent *hp, *gethostbyname();

  16.         /* Create socket on which to send. */
  17.         sock = socket(AF_INET, SOCK_DGRAM, 0);
  18.         if (sock < 0) {
  19.                 perror("opening datagram socket");
  20.                 exit(1);
  21.         }
  22.         /*
  23.          * Construct name, with no wildcards, of the socket
  24.          * to send to. Gethostbyname() returns a structure
  25.          * including the network address of the specified host.
  26.          * The port number is taken from the command line.
  27.          */
  28.         hp = gethostbyname(argv[1]);
  29.         if (hp == 0) {
  30.                 fprintf(stderr, "%s: unknown host0, argv[1]);
  31.                 exit(2);
  32.         }
  33.         memcpy(&name.sin_addr, hp->h_addr, hp->h_length);
  34.         name.sin_family = AF_INET;
  35.         name.sin_port = htons(atoi(argv[2]));
  36.         /* Send message. */
  37.         if (sendto(sock, DATA, sizeof(DATA), 0, &name,
  38.                      sizeof(name)) < 0)
  39.                 perror("sending datagram message

The format of the socket address, including the order of the bytes in the address, is specified in part by standards within the internet domain. Because machines differ in the internal representation they ordinarily use to represent integers, printing out the port number returned by getsockname() may result in a misinterpretation.

To print out the number, you must use the ntohs() function to convert the number from the network representation to the host's representation.

On some machines (e.g. 68000-based) this is a null operation; on others (e.g. ix86-based), it results in a swapping of bytes.

Another function, htons(), converts a short integer from the host format to the network format; similar functions exist for long integers. For more information, see the  entry in Chapter 5, TCP/IP Libraries.

For data to be sent between stream sockets (i.e. sockets using the SOCK_STREAM communication style), the sockets must be “connected.” The two example programs below show you how to create such a connection.

The first program initiates a connection by creating a stream socket. It then calls connect(), specifying the address of the target socket it wishes to connect its socket to. If the target socket exists and is prepared to handle a connection, the connection will be completed, and the program can start sending messages. As with pipes, messages will be delivered in order, without message boundaries.

The connection is destroyed when either socket is closed. If a process persists in sending messages after the connection is closed, a SIGPIPE signal is sent to the process. Unless explicit action is taken to handle the signal (see signal() or sigvec()), the process will terminate.

Forming a stream connection is asymmetrical: one process (e.g. the first program below) requests a connection with a particular socket; the other process accepts connection requests. Before a connection can be accepted, a socket must be created and an address bound to it.

In the first example below, tut5.c is the client. It creates an unnamed socket and then connects to the server by using the specified command-line arguments (which are the values printed out by the server when it started up).

In the second example, tut6.c is the server; it creates a socket and binds a port number to it. It then prints out the port number that the client program needs to know. A connection may be destroyed by closing the corresponding socket.

The sample program below creates a socket and initiates a connection with the socket given in the command line. One message is sent over the connection and then the socket is closed, ending the connection. The form of the command line is:

点击(此处)折叠或打开

  1. tut5 hostname portnumber
  2. tut5.c

  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <netinet/in.h>
  6. #include <netdb.h>
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <unistd.h>

  11. #define DATA "Half a league, half a league..."

  12. main(argc, argv)
  13.         int argc;
  14.         char *argv[];
  15. {
  16.         int sock;
  17.         struct sockaddr_in server;
  18.         struct hostent *hp, *gethostbyname();
  19.         char buf[1024];

  20.         /* Create socket */
  21.         sock = socket(AF_INET, SOCK_STREAM, 0);
  22.         if (sock < 0) {
  23.                 perror("opening stream socket");
  24.                 exit(1);
  25.         }

  26.         /* Connect socket using name specified by command line. */
  27.         server.sin_family = AF_INET;
  28.         hp = gethostbyname(argv[1]);
  29.         if (hp == 0) {
  30.                 fprintf(stderr, "%s: unknown host0, argv[1]);
  31.                 exit(2);
  32.         }
  33.         memcpy(&server.sin_addr, hp->h_addr, hp->h_length);
  34.         server.sin_port = htons(atoi(argv[2]));

  35.         if (connect(sock, &server, sizeof(server)) < 0) {
  36.                 perror("connecting stream socket");
  37.                 exit(1);
  38.         }
  39.         if (write(sock, DATA, sizeof(DATA)) < 0)
  40.                 perror("writing on stream socket

The sample program below creates a socket and then begins an infinite loop. Each time through the loop it accepts a connection and prints out messages from it. When the connection breaks, or a termination message comes through, the program accepts a new connection.

Since this program has an infinite loop, the socket sock is never explicitly closed. However, all sockets are closed automatically when a process is killed or terminates normally.

点击(此处)折叠或打开

  1. tut6.c

  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <netdb.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include <stdlib.h>

  10. #define TRUE 1

  11. main()
  12. {
  13.         int sock, length;
  14.         struct sockaddr_in server;
  15.         int msgsock;
  16.         char buf[1024];
  17.         int rval;
  18.         int i;

  19.         /* Create socket */
  20.         sock = socket(AF_INET, SOCK_STREAM, 0);
  21.         if (sock < 0) {
  22.                 perror("opening stream socket");
  23.                 exit(1);
  24.         }

  25.         /* Name socket using wildcards */
  26.         server.sin_family = AF_INET;
  27.         server.sin_addr.s_addr = INADDR_ANY;
  28.         server.sin_port = 0;
  29.         if (bind(sock, &server, sizeof(server))) {
  30.                 perror("binding stream socket");
  31.                 exit(1);
  32.         }

  33.         /* Find out assigned port number and print it out */
  34.         length = sizeof(server);
  35.         if (getsockname(sock, &server, &length)) {
  36.                 perror("getting socket name");
  37.                 exit(1);
  38.         }
  39.         printf("Socket has port #%d\n", ntohs(server.sin_port));

  40.         /* Start accepting connections */
  41.         listen(sock, 5);
  42.         do {
  43.                 msgsock = accept(sock, 0, 0);
  44.                 if (msgsock == -1)
  45.                         perror("accept");
  46.                 else do {
  47.                         memset(buf, 0, sizeof(buf));
  48.                         if ((rval = read(msgsock, buf, 1024)) < 0)
  49.                                 perror("reading stream message");
  50.                         i = 0;
  51.                         if (rval == 0)
  52.                                 printf("Ending connection\n");
  53.                         else
  54.                                 printf("-->%s\n", buf);
  55.                 } while (rval != 0);
  56.                 close(msgsock);
  57.         } while (TRUE);
  58. }

 

The server program creates a socket, binds a name to the socket, and then prints out the socket number. The server then calls listen() for this socket. Since several clients may attempt to connect more or less simultaneously, a queue of pending connections is maintained in the system address space. The listen() call marks the socket as willing to accept connections and initializes the queue.

When a connection is requested, it's inserted in the queue. If the queue is full, an error status may be returned to the requester. The maximum length of this queue is specified by the second argument of listen() (and limited by the system). Once the listen call has been completed, the program enters an infinite loop. On each pass through the loop, a new connection is accepted and removed from the queue, and hence a new socket for the connection is created.

After the connection is created, the service (in this case printing out the messages) is performed and the connection socket is closed. The accept() call either takes a pending connection request from the queue (if one is available) or blocks, waiting for a request.

Messages are read from the connection socket. Reads from an active connection will normally block until data is available; the number of bytes read is returned. When a connection is destroyed, the read call returns immediately; the number of bytes returned is zero.

The following program is a slight variation on the previous server design — in this case, accept() won't block. The program calls select() first to check for pending requests before calling accept(). The select() will indicate when a connect request has occurred. This strategy is useful when connections may be received on more than one socket or when data may arrive on other connected sockets before another connection request.

点击(此处)折叠或打开

  1. tut7.c

  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <sys/time.h>
  5. #include <netinet/in.h>
  6. #include <sys/select.h>
  7. #include <netdb.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <unistd.h>
  11. #include <stdlib.h>

  12. #define TRUE 1

  13. main()
  14. {
  15.         int sock, length;
  16.         struct sockaddr_in server;
  17.         int msgsock;
  18.         char buf[1024];
  19.         int rval;
  20.         fd_set ready;
  21.         struct timeval to;
  22.         /* Create socket */
  23.         sock = socket(AF_INET, SOCK_STREAM, 0);
  24.         if (sock < 0) {
  25.                 perror("opening stream socket");
  26.                 exit(1);
  27.         }

  28.         /* Name socket using wildcards */
  29.         server.sin_family = AF_INET;
  30.         server.sin_addr.s_addr = INADDR_ANY;
  31.         server.sin_port = 0;
  32.         if (bind(sock, &server, sizeof(server))) {
  33.                 perror("binding stream socket");
  34.                 exit(1);
  35.         }

  36.         /* Find out assigned port number and print it out */
  37.         length = sizeof(server);
  38.         if (getsockname(sock, &server, &length)) {
  39.                 perror("getting socket name");
  40.                 exit(1);
  41.         }
  42.         printf("Socket has port #%d\n", ntohs(server.sin_port));

  43.         /* Start accepting connections */
  44.         listen(sock, 5);
  45.         do {
  46.                 FD_ZERO(&ready);
  47.                 FD_SET(sock, &ready);
  48.                 to.tv_sec = 5;
  49.                 if (select(sock + 1, &ready, 0, 0, &to) < 0) {
  50.                         perror("select");
  51.                         continue;
  52.                 }
  53.                 if (FD_ISSET(sock, &ready)) {
  54.                         msgsock = accept(sock, (struct sockaddr *)0, (int *)0);
  55.                         if (msgsock == -1)
  56.                                 perror("accept");
  57.                         else do {
  58.                                 memset(buf, 0, sizeof(buf));
  59.                                 if ((rval = read(msgsock, buf, sizeof(buf))) < 0)
  60.                                         perror("reading stream message");
  61.                                 else if (rval == 0)
  62.                                         printf("Ending connection\n");
  63.                                 else
  64.                                         printf("-->%s\n", buf);
  65.                         } while (rval > 0);
  66.                         close(msgsock);
  67.                 } else
  68.                         printf("Do something else\n");
  69.         } while (TRUE);
  70. }

You can use several functions for reading and writing information. The simplest of these are read() and write().

The write() function takes as arguments a descriptor, a pointer to a buffer containing the data, and the size of the data. The read() function takes a descriptor, a pointer to a buffer in which data can be placed, and the requested amount of data.

The descriptor can indicate either a file or a connected socket. “Connected” can mean either a datagram socket or a connected stream socket for which a connect() call has provided a default destination (see  in Chapter 5, TCP/IP Libraries).

Although the write() call requires a connected socket (no destination is specified in the call's parameters), read() can be used for either a connected or an unconnected socket. These calls are quite flexible; you can use them to write applications that require no assumptions about the source of their input or the destination of their output.

Two calls similar to read() and write() — readv() and writev() — allow the source and destination of the input and output to use several separate buffers, while retaining the flexibility to handle both files and sockets. The “v” in the names of these calls stands for “vector.”

Sometimes it's necessary to send high-priority data over a connection that may have unread low-priority data at the other end. For example, a user interface process may be interpreting commands and sending them on to another process through a stream connection. The user interface may have filled the stream with as yet unprocessed requests when the user types a command to cancel all outstanding requests. Rather than have the high-priority data wait to be processed after the low-priority data, you can have it sent as out-of-band (OOB) data.

The notification of pending OOB data results in the generation of a SIGURG signal, if this signal has been enabled. To enable this signal, you can use:

ioctl(fd, FIOASYNC, &value);

If value is nonzero, the signal is enabled.

To send and receive OOB information, you can use the send() and recv() calls, which are similar to write() and read(). You can use these calls only with sockets; specifying a descriptor for a file will result in the return of an error status. With these calls, you can also peek at data in a stream, i.e. they let a process read data without removing the data from the stream. One way you can use this facility is to read ahead in a stream to determine the size of the next item to be read.

To send datagrams using a call to sendto(), you must be able to specify the destination address as an argument.

The recvfrom() call is often used to read datagrams, since the call returns the address of the sender (if it's available) along with the data. If the sender's identity doesn't matter, you may use read() or recv().

Finally, to send and receive messages from multiple buffers, you use the sendmsg() and recvmsg() functions.

The various calls for reading and writing are shown below, together with their parameters. The parameters for each function reflect the differences in the behavior of the various calls. In the examples in this chapter, the calls read() and write() have been used whenever possible.

/* The variable descriptor may be the descriptor of either */ /* a file or a socket. */ int read(int descriptor, char *buf, int nbytes); int write(int descriptor, char *buf, int nbytes); /* An iovec can include several source buffers. */ int readv(int descriptor, struct iovec *iov, int iovcnt); int writev(int descriptor, struct iovec *iovec, int ioveclen); /* The variable "sock" must be the descriptor of a socket. */ /* Flags may include MSG_OOB, MSG_PEEK and MSG_WAITALL. */ int send(int sock, char *msg, int len, int flags); int sendto(int sock, char *msg, int len, int flags, struct sockaddr *to, int tolen); int sendmsg(int sock, struct msghdr msg[], int flags); int recv(int sock, char *buf, int len, int flags); int recvfrom(int sock, char *buf, int len, int flags, struct sockaddr *from; int *fromlen); int recvmsg(int sock, struct msghdr msg[], int flags );

We've discussed several forms of IPC. Let's now review the factors that make each attractive.

Pipes have the advantage of portability — they're supported in all UNIX systems. What's more, they're relatively simple to use.

The Socket Manager isn't required for pipe IPC.

Socketpairs are also simple to use, but have the additional advantage of allowing bidirectional communication. On the down side, however, socketpairs require communicating processes to be descendants of a common process.

Traditionally, both pipes and socketpairs were restricted for use between processes running on the same host. QNX's transparent LAN environment supports both IPC methods between processes running on different QNX nodes.

Internet domain sockets allow communication between machines where the underlying network is an internet. This makes internet sockets a necessary choice for communication between processes running on QNX and processes running on other machines connected to the internet.

Choosing between datagrams and stream communication requires that you carefully consider the semantic and performance requirements of the application.

Streams have both disadvantages and advantages. One disadvantage is that the number of available file descriptors may be limited by the system (see the -f option to Proc32); this can cause problems if a single server must talk with a large number of clients. Another disadvantage is that for delivering a short message, the stream setup and tear-down time can be unnecessarily long.

On the other hand, streams have the advantage of built-in reliability, and this often becomes the deciding factor in choosing streams over datagrams.

阅读(627) | 评论(0) | 转发(0) |
0

上一篇:桔梗

下一篇:快排的一个实现

给主人留下些什么吧!~~