GRASS Programmer's Manual  6.5.svn(2014)-r66266
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
connect_sock.c
Go to the documentation of this file.
1 
2 #include <grass/config.h>
3 
4 #ifdef HAVE_SOCKET
5 
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 
14 #include <grass/gis.h>
15 #include "driverlib.h"
16 
17 int prepare_connection_sock(const char *me)
18 {
19  const char *connpath;
20  int fd;
21 
22  connpath = G_sock_get_fname(me);
23  if (!connpath)
24  G_fatal_error("Couldn't get socket path");
25 
26  /* Now we must check and see whether or not someone */
27  /* (possibly another invocation of ourself) is using our socket. */
28 
29  if (G_sock_exists(connpath)) {
30  if ((fd = G_sock_connect(connpath)) >= 0) {
31  close(fd);
32  G_warning("Graphics driver [%s] is already running", me);
33  G_fatal_error("Unable to start monitor <%s>", me);
34  }
35 
36  if (unlink(connpath) < 0) {
37  G_warning("Failed to remove stale socket file: %s", connpath);
38  G_fatal_error("Unable to start monitor <%s>", me);
39  }
40  }
41 
42  /* We are free to run now. No one is using our socket. */
43  if ((fd = G_sock_bind(connpath)) < 0) {
44  G_fatal_error("Can't bind to socket: error \"%s\"\n",
45  strerror(errno));
46  }
47 
48  /* Now set up listen */
49  if (G_sock_listen(fd, 1) != 0) {
50  G_fatal_error("G_sock_listen: error \"%s\"\n", strerror(errno));
51  }
52 
53  return fd;
54 }
55 
56 int get_connection_sock(int listenfd, int *rfd, int *wfd, int other_fd)
57 {
58  int fd;
59 
60 #ifndef __MINGW32__
61  if (other_fd >= 0) {
62  fd_set waitset;
63 
64  FD_ZERO(&waitset);
65  FD_SET(listenfd, &waitset);
66  FD_SET(other_fd, &waitset);
67  if (select(FD_SETSIZE, &waitset, NULL, NULL, NULL) < 0) {
68  perror("get_connection_sock: select");
69  exit(EXIT_FAILURE);
70  }
71 
72  if (!FD_ISSET(listenfd, &waitset))
73  return -1;
74  }
75 #endif
76 
77  /* G_sock_accept will block until a connection is requested */
78  fd = G_sock_accept(listenfd);
79  if (fd >= 0) {
80  *rfd = fd;
81  *wfd = dup(fd);
82  return 0;
83  }
84 
85  if (errno == EINTR)
86  return -1;
87 
88  G_warning("G_sock_accept: error \"%s\"", strerror(errno));
90  exit(EXIT_FAILURE);
91 }
92 
93 #endif /* HAVE_SOCKET */
FILE * fd
Definition: g3dcolor.c:368
void COM_Graph_close(void)
Definition: driver/Graph.c:11
int get_connection_sock(int, int *, int *, int)
int prepare_connection_sock(const char *)
return NULL
Definition: dbfopen.c:1394
G_warning("category support for [%s] in mapset [%s] %s", name, mapset, type)
int errno
int G_fatal_error(const char *msg,...)
Print a fatal error message to stderr.