Example #1
0
void SocketTransport::listenForClientConnection() {
  // If there was a previous connection in the base class, shut it down.
  // This will close the old transport and wait for both the send and receive
  // worker threads to terminate before proceeding.
  if (getTransportFd() >= 0) {
    shutdown();
  }

  VSDebugLogger::Log(
    VSDebugLogger::LogLevelInfo,
    "SocketTransport worker thread listening for connections..."
  );

  int abortFd;
  {
    Lock lock(m_lock);
    abortFd = m_abortPipeFd[0];
    assertx(abortFd >= 0);
  }

  struct addrinfo hint;
  struct addrinfo* ai = nullptr;
  std::vector<int> socketFds;

  memset(&hint, 0, sizeof(hint));
  hint.ai_family = AF_UNSPEC;
  hint.ai_socktype = SOCK_STREAM;
  hint.ai_flags = AI_PASSIVE;

  SCOPE_EXIT {
    if (ai != nullptr) {
      freeaddrinfo(ai);
    }

    for (auto it = socketFds.begin(); it != socketFds.end(); it++) {
      close(*it);
    }

    close(abortFd);
    m_abortPipeFd[0] = -1;

    VSDebugLogger::Log(
      VSDebugLogger::LogLevelInfo,
      "SocketTransport connection polling thread exiting."
    );
  };

  // Share existing DebuggerDisableIPv6 configuration with hphpd.
  if (RuntimeOption::DebuggerDisableIPv6) {
    hint.ai_family = AF_INET;
  }

  const auto name = RuntimeOption::DebuggerServerIP.empty()
    ? "localhost"
    : RuntimeOption::DebuggerServerIP.c_str();
  if (getaddrinfo(name, std::to_string(m_listenPort).c_str(), &hint, &ai)) {
    VSDebugLogger::Log(
      VSDebugLogger::LogLevelError,
      "Failed to call getaddrinfo: %d.",
      errno
    );

    return;
  }

  // Attempt to listen on the specified port on each of this host's available
  // addresses.
  struct addrinfo* address;
  bool anyInterfaceBound = false;
  for (address = ai; address != nullptr; address = address->ai_next) {
    if (bindAndListen(address, socketFds)) {
      anyInterfaceBound = true;
    }
  }

  if (!anyInterfaceBound) {
    VSDebugLogger::Log(
      VSDebugLogger::LogLevelWarning,
      "Debugger failed to bind to any interface!"
    );
    return;
  } else {
    VSDebugLogger::Log(
      VSDebugLogger::LogLevelInfo,
      "Debugger bound to at least one interface."
    );
  }

  waitForConnection(socketFds, abortFd);
}
Example #2
0
int OpenComport(int comport_number, int baudrate)
{
    int baudr;

    if((comport_number>21)||(comport_number<0))
    {
        printf("illegal comport number\n");
        return(1);
    }

    switch(baudrate)
    {
    case      50 :
        baudr = B50;
        break;
    case      75 :
        baudr = B75;
        break;
    case     110 :
        baudr = B110;
        break;
    case     134 :
        baudr = B134;
        break;
    case     150 :
        baudr = B150;
        break;
    case     200 :
        baudr = B200;
        break;
    case     300 :
        baudr = B300;
        break;
    case     600 :
        baudr = B600;
        break;
    case    1200 :
        baudr = B1200;
        break;
    case    1800 :
        baudr = B1800;
        break;
    case    2400 :
        baudr = B2400;
        break;
    case    4800 :
        baudr = B4800;
        break;
    case    9600 :
        baudr = B9600;
        break;
    case   19200 :
        baudr = B19200;
        break;
    case   38400 :
        baudr = B38400;
        break;
    case   57600 :
        baudr = B57600;
        break;
    case  115200 :
        baudr = B115200;
        break;
    case  230400 :
        baudr = B230400;
        break;
    case  460800 :
        baudr = B460800;
        break;
    case  500000 :
        baudr = B500000;
        break;
    case  576000 :
        baudr = B576000;
        break;
    case  921600 :
        baudr = B921600;
        break;
    case 1000000 :
        baudr = B1000000;
        break;
    default      :
        printf("invalid baudrate\n");
        return(1);
        break;
    }

    Cport[comport_number] = open(comports[comport_number], O_RDWR | O_NOCTTY | O_NDELAY);
    if(Cport[comport_number]==-1)
    {
        perror("unable to open comport ");
        return(1);
    }

    error = tcgetattr(Cport[comport_number], old_port_settings + comport_number);
    if(error==-1)
    {
        close(Cport[comport_number]);
        perror("unable to read portsettings ");
        return(1);
    }
    memset(&new_port_settings, 0, sizeof(new_port_settings));  /* clear the new struct */

    new_port_settings.c_cflag = baudr | CS8 | CLOCAL | CREAD;
    new_port_settings.c_iflag = IGNPAR;
    new_port_settings.c_oflag = 0;
    new_port_settings.c_lflag = 0;
    new_port_settings.c_cc[VMIN] = 0;      /* block untill n bytes are received */
    new_port_settings.c_cc[VTIME] = 0;     /* block untill a timer expires (n * 100 mSec.) */
    error = tcsetattr(Cport[comport_number], TCSANOW, &new_port_settings);
    if(error==-1)
    {
        close(Cport[comport_number]);
        perror("unable to adjust portsettings ");
        return(1);
    }

    return(0);
}
Example #3
0
/*
 * Make a pack stream and spit it out into file descriptor fd
 */
static int pack_objects(int fd, struct ref *refs, struct sha1_array *extra, struct send_pack_args *args)
{
	/*
	 * The child becomes pack-objects --revs; we feed
	 * the revision parameters to it via its stdin and
	 * let its stdout go back to the other end.
	 */
	const char *argv[] = {
		"pack-objects",
		"--all-progress-implied",
		"--revs",
		"--stdout",
		NULL,
		NULL,
		NULL,
		NULL,
		NULL,
		NULL,
	};
	struct child_process po = CHILD_PROCESS_INIT;
	int i;

	i = 4;
	if (args->use_thin_pack)
		argv[i++] = "--thin";
	if (args->use_ofs_delta)
		argv[i++] = "--delta-base-offset";
	if (args->quiet || !args->progress)
		argv[i++] = "-q";
	if (args->progress)
		argv[i++] = "--progress";
	if (is_repository_shallow())
		argv[i++] = "--shallow";
	po.argv = argv;
	po.in = -1;
	po.out = args->stateless_rpc ? -1 : fd;
	po.git_cmd = 1;
	if (start_command(&po))
		die_errno("git pack-objects failed");

	/*
	 * We feed the pack-objects we just spawned with revision
	 * parameters by writing to the pipe.
	 */
	for (i = 0; i < extra->nr; i++)
		if (!feed_object(extra->sha1[i], po.in, 1))
			break;

	while (refs) {
		if (!is_null_sha1(refs->old_sha1) &&
		    !feed_object(refs->old_sha1, po.in, 1))
			break;
		if (!is_null_sha1(refs->new_sha1) &&
		    !feed_object(refs->new_sha1, po.in, 0))
			break;
		refs = refs->next;
	}

	close(po.in);

	if (args->stateless_rpc) {
		char *buf = xmalloc(LARGE_PACKET_MAX);
		while (1) {
			ssize_t n = xread(po.out, buf, LARGE_PACKET_MAX);
			if (n <= 0)
				break;
			send_sideband(fd, -1, buf, n, LARGE_PACKET_MAX);
		}
		free(buf);
		close(po.out);
		po.out = -1;
	}

	if (finish_command(&po))
		return -1;
	return 0;
}
Example #4
0
int main(int argc, char const * const argv[])
{
	if (2 >= argc) {
		fprintf(stderr,
			"Usage: %s device baud "
				"[databits=8 [parity=N [stopbits=1]]]\n",
			argv[0]);
		return -1;
	}
        char const *const deviceName = argv[1];
        int const fdSerial = open(deviceName, O_RDWR);
        if (0 > fdSerial) {
		perror(deviceName);
		return -1;
	}
	fcntl(fdSerial, F_SETFD, FD_CLOEXEC);
	fcntl(fdSerial, F_SETFL, O_NONBLOCK);

	int baud = strtoul(argv[2], 0, 0);
	int databits = ((3 < argc) && (7 == strtoul(argv[3], 0, 0)))
		       ? 7
		       : 8 ;
	char parity = (4 < argc)
		      ? toupper(*argv[4])
		      : 'N' ;
	unsigned stopBits = ((5 < argc) && ('2' == *argv[5]))
			    ? 2
			    : 1 ;

	printf("device %s opened: %u baud, %d bits, parity %c\n", deviceName, baud, databits, parity);
	struct termios oldSerialState;
	setRaw(fdSerial, baud, databits, parity, stopBits, oldSerialState);

	struct termios oldStdinState;
	tcgetattr(0,&oldStdinState);
	/* set raw mode for keyboard input */
	struct termios newState = oldStdinState;
	newState.c_cc[VMIN] = 1;


	newState.c_lflag &= ~(ICANON | ECHO);				 // set raw mode for input
	newState.c_iflag &= ~(IXON | IXOFF | IXANY|INLCR|ICRNL|IUCLC);	 //no software flow control
	newState.c_oflag &= ~OPOST;			 //raw output
	tcsetattr(0, TCSANOW, &newState);

	signal(SIGINT, ctrlcHandler);
	pollfd fds[2];
	fds[0].fd = fdSerial ;
	fds[0].events = POLLIN | POLLERR ;
	fds[1].fd = fileno(stdin);
	fds[1].events = POLLIN | POLLERR ;

	while (!doExit) {
		::poll(fds, 2, 1000);
		for (unsigned i = 0 ; i < 2 ; i++) {
                        if (fds[i].revents & POLLIN) {
				char inBuf[80];
				int numRead = read(fds[i].fd, inBuf, sizeof(inBuf));
				if (0 < numRead) {
					int fdout = i ? fdSerial : 1;
					write(fdout,inBuf,numRead);
				}
			}
		}
	}

	tcsetattr(fdSerial, TCSANOW, &oldSerialState);
	tcsetattr(0, TCSANOW, &oldStdinState);

	close(fdSerial);
	return 0 ;
}
Example #5
0
Data * ZipFileSystem :: readEntry ( const ZipCentralHeader& hdr )
{
	int	size = 0;
	int	file = open ( fileName.c_str (), O_BINARY | O_RDONLY );

	if ( file == -1 )
		return NULL;

	if ( lseek ( file, hdr.relativeLocalHeaderOffset, SEEK_SET ) != hdr.relativeLocalHeaderOffset )
	{
		close ( file );

		return NULL;
	}

	ZipLocalFileHeader	localHdr;

	if ( read ( file, &localHdr, sizeof ( localHdr ) ) != sizeof ( localHdr ) )
	{
		close ( file );

		return NULL;
	}

	if ( localHdr.signature != LOCAL_ZIP_SIGNATURE )
	{
		close ( file );

		return NULL;
	}

	lseek ( file, localHdr.filenameLength + localHdr.extraFieldLength, SEEK_CUR );

	char	inBuffer [2048];
	size_t	blockSize;
	size_t	bytesLeft = hdr.compressedSize;
	void  * buf       = calloc ( 1, hdr.uncompressedSize + 1 );
	int		err       = 0;

	switch ( hdr.compressionMethod )
	{
		case ZIP_STORE:
			if ( read ( file, buf, hdr.compressedSize ) != hdr.compressedSize )
			{
				free  ( buf );
				close ( file );

				return NULL;
			}

			break;

		case ZIP_DEFLATE:
			z_stream	zs;

			memset ( &zs, '\0', sizeof ( zs ) );

			zs.next_out  = (unsigned char *)buf;
			zs.avail_out = hdr.uncompressedSize;
			zs.zalloc    = NULL;
			zs.zfree     = NULL;

			if ( inflateInit2 ( &zs, -DEF_WBITS ) != Z_OK )
			{
				free  ( buf  );
				close ( file );

				return NULL;
			}

			while ( bytesLeft > 0 )
			{
				blockSize   = bytesLeft > sizeof ( inBuffer ) ? sizeof ( inBuffer ) : bytesLeft;
				zs.next_in  = (unsigned char *)inBuffer;
				zs.avail_in = read ( file, inBuffer, blockSize );

				err        = inflate ( &zs, bytesLeft >= blockSize ? Z_PARTIAL_FLUSH : Z_FINISH );
				bytesLeft -= blockSize;
			}

			inflateEnd ( &zs );

			if ( err < 0 )
			{
				free  ( buf  );
				close ( file );

				return NULL;
			}

			break;

		default:
			free  ( buf );
			close ( file );

			return NULL;
	}

	close ( file );

	size = hdr.uncompressedSize;

	return new Data ( buf, size );
}
int main(int argc, char **argv)
{
  CURL *curl;
  CURLcode res;
  intptr_t hd ;
  struct stat file_info;

  char *file;
  char *url;

  if(argc < 3)
    return 1;

  file= argv[1];
  url = argv[2];

  /* get the file size of the local file */
  hd = open(file, O_RDONLY) ;
  fstat(hd, &file_info);

  /* In windows, this will init the winsock stuff */
  curl_global_init(CURL_GLOBAL_ALL);

  /* get a curl handle */
  curl = curl_easy_init();
  if(curl) {
    /* we want to use our own read function */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

    /* which file to upload */
    curl_easy_setopt(curl, CURLOPT_READDATA, (void*)hd);

    /* set the ioctl function */
    curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, my_ioctl);

    /* pass the file descriptor to the ioctl callback as well */
    curl_easy_setopt(curl, CURLOPT_IOCTLDATA, (void*)hd);

    /* enable "uploading" (which means PUT when doing HTTP) */
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L) ;

    /* specify target URL, and note that this URL should also include a file
       name, not only a directory (as you can do with GTP uploads) */
    curl_easy_setopt(curl,CURLOPT_URL, url);

    /* and give the size of the upload, this supports large file sizes
       on systems that have general support for it */
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
    			(curl_off_t)file_info.st_size);

    /* tell libcurl we can use "any" auth, which lets the lib pick one, but it
       also costs one extra round-trip and possibly sending of all the PUT
       data twice!!! */
    curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_ANY);

    /* set user name and password for the authentication */
    curl_easy_setopt(curl, CURLOPT_USERPWD, "user:password");

    /* Now run off and do what you've been told! */
    res = curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  close(hd); /* close the local file */

  curl_global_cleanup();
  return 0;
}
Example #7
0
int
ssvm_slave_init_shm (ssvm_private_t * ssvm)
{
  struct stat stat;
  int ssvm_fd = -1;
  ssvm_shared_header_t *sh;

  ASSERT (vec_c_string_is_terminated (ssvm->name));
  ssvm->i_am_master = 0;

  while (ssvm->attach_timeout-- > 0)
    {
      if (ssvm_fd < 0)
	ssvm_fd = shm_open ((char *) ssvm->name, O_RDWR, 0777);
      if (ssvm_fd < 0)
	{
	  sleep (1);
	  continue;
	}
      if (fstat (ssvm_fd, &stat) < 0)
	{
	  sleep (1);
	  continue;
	}

      if (stat.st_size > 0)
	goto map_it;
    }
  clib_warning ("slave timeout");
  return SSVM_API_ERROR_SLAVE_TIMEOUT;

map_it:
  sh = (void *) mmap (0, MMAP_PAGESIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
		      ssvm_fd, 0);
  if (sh == MAP_FAILED)
    {
      clib_unix_warning ("slave research mmap");
      close (ssvm_fd);
      return SSVM_API_ERROR_MMAP;
    }

  while (ssvm->attach_timeout-- > 0)
    {
      if (sh->ready)
	goto re_map_it;
    }
  close (ssvm_fd);
  munmap (sh, MMAP_PAGESIZE);
  clib_warning ("slave timeout 2");
  return SSVM_API_ERROR_SLAVE_TIMEOUT;

re_map_it:
  ssvm->requested_va = sh->ssvm_va;
  ssvm->ssvm_size = sh->ssvm_size;
  munmap (sh, MMAP_PAGESIZE);

  sh = ssvm->sh = (void *) mmap ((void *) ssvm->requested_va, ssvm->ssvm_size,
				 PROT_READ | PROT_WRITE,
				 MAP_SHARED | MAP_FIXED, ssvm_fd, 0);

  if (sh == MAP_FAILED)
    {
      clib_unix_warning ("slave final mmap");
      close (ssvm_fd);
      return SSVM_API_ERROR_MMAP;
    }
  sh->slave_pid = getpid ();
  return 0;
}
Example #8
0
int
main (void)
{
  /* Remove any leftovers from a previous partial run.  */
  ignore_value (system ("rm -rf " BASE "*"));

  /* Setup.  */
  ASSERT (mkdir (BASE "dir", 0700) == 0);
  ASSERT (close (creat (BASE "dir/file", 0600)) == 0);

  /* Basic error conditions.  */
  errno = 0;
  ASSERT (remove ("") == -1);
  ASSERT (errno == ENOENT);
  errno = 0;
  ASSERT (remove ("nosuch") == -1);
  ASSERT (errno == ENOENT);
  errno = 0;
  ASSERT (remove ("nosuch/") == -1);
  ASSERT (errno == ENOENT);
  errno = 0;
  ASSERT (remove (".") == -1);
  ASSERT (errno == EINVAL || errno == EBUSY);
  /* Resulting errno after ".." or "/" is too varied to test; it is
     reasonable to see any of EINVAL, EEXIST, ENOTEMPTY, EACCES.  */
  ASSERT (remove ("..") == -1);
  ASSERT (remove ("/") == -1);
  ASSERT (remove ("///") == -1);
  errno = 0;
  ASSERT (remove (BASE "dir/file/") == -1);
  ASSERT (errno == ENOTDIR);

  /* Non-empty directory.  */
  errno = 0;
  ASSERT (remove (BASE "dir") == -1);
  ASSERT (errno == EEXIST || errno == ENOTEMPTY);

  /* Non-directory.  */
  ASSERT (remove (BASE "dir/file") == 0);

  /* Empty directory.  */
  errno = 0;
  ASSERT (remove (BASE "dir/.//") == -1);
  ASSERT (errno == EINVAL || errno == EBUSY);
  ASSERT (remove (BASE "dir") == 0);

  /* Test symlink behavior.  Specifying trailing slash should remove
     referent directory, or cause ENOTDIR failure, but not touch
     symlink.  */
  if (symlink (BASE "dir", BASE "link") != 0)
    {
      fputs ("skipping test: symlinks not supported on this file system\n",
             stderr);
      return 77;
    }
  ASSERT (mkdir (BASE "dir", 0700) == 0);
  errno = 0;
  if (remove (BASE "link/") == 0)
    {
      struct stat st;
      errno = 0;
      ASSERT (stat (BASE "link", &st) == -1);
      ASSERT (errno == ENOENT);
    }
  else
    ASSERT (remove (BASE "dir") == 0);
  {
    struct stat st;
    ASSERT (lstat (BASE "link", &st) == 0);
    ASSERT (S_ISLNK (st.st_mode));
  }
  ASSERT (remove (BASE "link") == 0);
  /* Trailing slash on symlink to non-directory is an error.  */
  ASSERT (symlink (BASE "loop", BASE "loop") == 0);
  errno = 0;
  ASSERT (remove (BASE "loop/") == -1);
  ASSERT (errno == ELOOP || errno == ENOTDIR);
  ASSERT (remove (BASE "loop") == 0);
  ASSERT (close (creat (BASE "file", 0600)) == 0);
  ASSERT (symlink (BASE "file", BASE "link") == 0);
  errno = 0;
  ASSERT (remove (BASE "link/") == -1);
  ASSERT (errno == ENOTDIR);
  ASSERT (remove (BASE "link") == 0);
  ASSERT (remove (BASE "file") == 0);

  return 0;
}
Example #9
0
int main(int argc, char **argv)
{
    int sfd = 0, s = 0;
    int efd = 0;
    struct epoll_event event = {};
    struct epoll_event *events = NULL;

    if (argc != 2)
    {
        fprintf(stderr, "usage: %s [port]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    sfd = create_and_bind(argv[1]);
    if (sfd == -1) {abort();}
    fprintf(stdout, "sfd: %d\n", sfd);

    s = make_socket_non_blocking(sfd);
    if (s == -1) {abort();}

    s = listen(sfd, SOMAXCONN);
    if (s == -1)
    {
        perror("listen");
        abort();
    }

    efd = epoll_create(256);
    if (efd == -1)
    {
        perror("epoll_create1");
        abort();
    }

    event.data.fd = sfd;
    event.events = EPOLLIN | EPOLLET;
    s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
    if (s == -1)
    {
        perror("epoll_ctl");
        abort();
    }

    //Buffer where events are returned
    events = calloc(MAXEVENTS, sizeof(event));

    fprintf(stdout, "before event loop\n");
    //The event loop
    while (1)
    {
        int n, i;

        n = epoll_wait(efd, events, MAXEVENTS, -1);
        fprintf(stdout, "epoll wait return: %d\n", n);
        for (i=0; i<n; i++)
        {
            fprintf(stdout, "events[%d].data.fd=%d\n", i, events[i].data.fd);
            if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP)
                    || (!(events[i].events & EPOLLIN)))
            {
                //an error has occured on this fd, or the socket is not ready for reading
                fprintf(stderr, "epoll error\n");
                close(events[i].data.fd);
                continue;
            }
            else if (sfd == events[i].data.fd)
            {
                //we have a notification on the listening socket, which means one or more
                //incoming connections
                fprintf(stdout, "sfd == events[i].data.fd\n");
                while (1)
                {
                    struct sockaddr in_addr = {};
                    socklen_t in_len = 0;
                    int infd = 0;
                    char hbuf[NI_MAXHOST] = {}, sbuf[NI_MAXSERV] = {};

                    in_len = sizeof(in_addr);
                    infd = accept(sfd, &in_addr, &in_len);
                    if (infd == -1)
                    {
                        if (errno == EAGAIN || errno == EWOULDBLOCK)
                        {
                            //we have processed all incoming connections
                            fprintf(stderr, "accept error: %d\n", errno);
                            break;
                        }
                        else
                        {
                            perror("accept");
                            break;
                        }
                    }
                    fprintf(stdout, "infd=%d\n", infd);

                    s = getnameinfo(&in_addr, in_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), 
                            NI_NUMERICHOST | NI_NUMERICSERV);
                    if (s == 0)
                    {
                        printf("accepted connection on descriptor %d (host=%s, port=%s)\n", 
                                infd, hbuf, sbuf);
                    }

                    fprintf(stdout, "getnameinfo return s:%d\n", s);
                    //make the incoming socket non-blocking and add it to the list of fds
                    //to monitor
                    s = make_socket_non_blocking(infd);
                    if (s == -1) {abort();}

                    event.data.fd = infd;
                    event.events = EPOLLIN | EPOLLET;
                    s = epoll_ctl(efd, EPOLL_CTL_ADD, infd, &event);
                    if (s == -1)
                    {
                        perror("epoll_ctl");
                        abort();
                    }
                }
                continue;
            }
            else
            {
                //we have data on the fd waiting to be read. Read and display it. We must read
                //whatever data is available completely, as we are running in edge-triggered 
                //mode and won't get a notification again for the same data
                int done = 0;
                
                fprintf(stdout, "else\n");
                while (1)
                {
                    ssize_t count = 0;
                    char buf[512] = "hello epoll";

                    count  = read(events[i].data.fd, buf, sizeof(buf));
                    fprintf(stdout, "read return count=%d\n", count);
                    if (count == -1)
                    {
                        //if errno == EAGAIN , that means we have read all data.
                        //So go back to the main loop
                        fprintf(stdout, "count==-1, errno:%d\n", errno);
                        if (errno != EAGAIN)
                        {
                            perror("read");
                            done = 1;
                        }
                        break;
                    }
                    else if (count == 0)
                    {
                        //end of file. The remote has closed the connection
                        fprintf(stdout, "count == 0\n");
                        done = -1;
                        break;
                    }

                    printf("read data: %s\n", buf);
                    //write the buffer to standard output
                    s = write(STDOUT_FILENO, buf, count);
                    if (s == -1)
                    {
                        perror("write");
                        abort();
                    }
                }

                if (done)
                {
                    printf("closed connection on descriptor %d\n", events[i].data.fd);

                    //closing the descriptor will make epoll remove it from the set of
                    //descriptors which are monitored
                    close(events[i].data.fd);
                }
            }
        }
    }

    free(events);
    events = NULL;
    close(sfd);

    return EXIT_SUCCESS;
}
Example #10
0
int
main(int argc, char *argv[])
{
	pid_t 	pid;
	int		status;
  int   ServerFD[2];
  int   ServerFD2[2];
  char  *data = "accept";
  char  *data2 = "reject";
  char  *terminate = "terminate";
  char  pubbuf[1025];
  char  pubbufend[1025];
  char  pubbufterm[1025];
  char  subbuf[1025];
  char  subbufend[1025];
  char  subbufterm[1025];

  pipe(ServerFD);
  pipe(ServerFD2);
	pid = fork();

	if(pid == 0){//this is the child of the main process, the DIServer
    int i;
		//n is # of publisher
		int n = atoi(argv[1]);
		//m is number of subscribers
		int m = atoi(argv[2]);
    //t are topics	
    int t = atoi(argv[3]);
    pthread_t pubthreads[n];
    pthread_t subthreads[m];
    int   rc;
    int   rc2;
    void  *pubthreadstatus;
    void  *subthreadstatus;

    pthread_attr_t pubattr;
    pthread_attr_t subattr;

    pthread_attr_init(&pubattr);
    pthread_attr_setdetachstate(&pubattr, PTHREAD_CREATE_JOINABLE);

    pthread_attr_init(&subattr);
    pthread_attr_setdetachstate(&subattr, PTHREAD_CREATE_JOINABLE);

    pthread_mutex_init(&mutexlock,NULL);


    Record record[n+m];
		/*need to use n and m to create child procs of the 
		DIServer, publishers and subscriers*/
		//loop to create publisher procs and stroe pid in array;
		pid_t pubpid;
		pid_t subpid;

		//map space for the pub array
		pubpids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
              MAP_SHARED | MAP_ANONYMOUS, -1, 0);
		 if (!pubpids) {
    		perror("mmap failed");
    		exit(1);
 		 }
  		memset((void *)pubpids, 0, MAX_PIDS*sizeof(pid_t)); 		 
 		 //map space for sub array
		subpids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
              MAP_SHARED | MAP_ANONYMOUS, -1, 0);
		 if (!subpids) {
    		perror("mmap failed");
    		exit(1);
 		 }
  		memset((void *)subpids, 0, MAX_PIDS*sizeof(pid_t));

  		//loop to creat forked pubs
  		for(i=0;i<n;i++)
  		{
        //create the record struct
        //create the publisher struct
        int z;
        Publisher pub;
        pub.pubConnect = "Pub Connect";
        pub.pubTopic = "Topic 1";//topic of interest
        pub.pubEnd = "End";
        pub.pubterm = "terminate";
        pipe(pub.fileDescriptor);
  			pubpid = fork();
        int articles;
        char article[12];
  			if(pubpid == 0)
  			{
          //doPublisher(n);
          write(pub.fileDescriptor[1], pub.pubConnect, strlen(pub.pubConnect));
          if ((z = read(ServerFD[0], pubbuf, 1024)) >= 0) {
              pubbuf[z] = 0; /* terminate the string */ 
              //printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbuf);
              if (strcmp(pubbuf, data) == 0)
              {
                write(pub.fileDescriptor[1], pub.pubTopic, strlen(pub.pubTopic));
                if ((z = read(ServerFD[0], pubbufend, 1024)) >= 0) {
                  pubbufend[z] = 0;
                  //printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbufend);
                  if (strcmp(pubbufend, data) == 0){
                    write(pub.fileDescriptor[1], pub.pubEnd, strlen(pub.pubEnd));
                    if((z = read(ServerFD[0], pubbufend, 1024)) >= 0) {
                     // printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbufend);
                      /*if (strcmp(pubbufend, data)==0){
                        for (articles = 0; articles<10;articles++){
                          if(articles%2 != 0){
                            sprintf(article, "Topic 1 Article %d", articles);
                            write(pub.fileDescriptor[1], article, strlen(article));
                          }
                        }
                      }*/
                    }

                  }
                  else{
                    write(pub.fileDescriptor[1], pub.pubterm, strlen(pub.pubterm));
                    continue;
                 }
                }
              }
              else{
                write(pub.fileDescriptor[1], pub.pubterm, strlen(pub.pubterm));
                continue;
              }

          } 
          else 
              perror("read");
          //if reads accept then write to publisher pipe 
  				exit(0);
  			}
  			else if (pubpid < 0){
  				perror("fork failed");
  			}
        
  			else{//back to the DIServer

          record[i].pipe = pub.fileDescriptor;
          record[i].type = "Publisher";
          record[i].pid = i+1;
          record[i].selectTopics = pub.pubTopic;
          record[i].serverPipe = ServerFD;
          rc=pthread_create(&pubthreads[i],&pubattr,pubThr_fn,(void *) &record[i]);
          if(rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
          }
          pthread_attr_destroy(&pubattr);
          rc = pthread_join(pubthreads[i], &pubthreadstatus);
          // want to create the thread here, then handle all of reading a writng of pipes in thread handler}
  		  }
      }

  		//loop to create forked subs;
      for(i=0;i<m;i++)
      {
        //create the subscriber struct
        int z;
        Subscriber sub;
        sub.subConnect = "Sub Connect";
        sub.subTopic = "Topic 1"; //topic of interest
        sub.subEnd = "End";
        sub.subterm = "terminate";
        pipe(sub.fileDescriptor);
        subpid = fork();
        if(subpid == 0)
        {
          //doPublisher(n);
          write(sub.fileDescriptor[1], sub.subConnect, strlen(sub.subConnect));
          if ((z = read(ServerFD2[0], subbuf, 1024)) >= 0) {
              subbuf[z] = 0; /* terminate the string */ 
              //printf("sub read %d bytes from the DIServer pipe: \"%s\"\n", z, subbuf);
              if (strcmp(subbuf, data) == 0)
              {
                write(sub.fileDescriptor[1], sub.subTopic, strlen(sub.subTopic));
                if ((z = read(ServerFD2[0], subbufend, 1024)) >= 0) {
                  subbufend[z] = 0;
                 // printf("sub read %d bytes from the DIServer pipe: \"%s\"\n", z, subbufend);
                  if (strcmp(subbufend, data) == 0){
                    write(sub.fileDescriptor[1], sub.subEnd, strlen(sub.subEnd));
                    if((z = read(ServerFD2[0], subbufend, 1024)) >= 0) {
                      //printf("sub read %d bytes from the DIServer pipe: \"%s\"\n", z, subbufend);
                    }
                  }
                  else{
                    write(sub.fileDescriptor[1], sub.subterm, strlen(sub.subterm));
                    continue;
                 }
                }
              }
              else{
                write(sub.fileDescriptor[1], sub.subterm, strlen(sub.subterm));
                continue;
              }

          } 
          else 
              perror("read");
          //if reads accept then write to publisher pipe 
          exit(0);
        }
        else if (subpid < 0){
          perror("fork failed");
        }
        else{//back to the DIServer
          record[i+n].pipe = sub.fileDescriptor;
          record[i+n].type = "Subscriber";
          record[i+n].pid = i+1;
          record[i+n].selectTopics = sub.subTopic;
          record[i+n].serverPipe = ServerFD2;

          rc2 = pthread_create(&subthreads[i],&subattr,subThr_fn,(void *) &record[i+n]);
          if(rc2){
            printf("ERROR; return code from pthread_create() is %d\n", rc2);
            exit(-1);
          }
          pthread_attr_destroy(&subattr);
          rc2 = pthread_join(subthreads[i], &subthreadstatus);


        }
      }
      /*
      pthread_attr_destroy(&subattr);
      for(i=0;i<n;i++){
        printf("here\n");
        rc = pthread_join(pubthreads[i], &pubthreadstatus);
        if (rc) {
          printf("ERROR; return code from pthread_join() is %d\n", rc);
          exit(-1);
        }
      }
      pthread_attr_destroy(&subattr);
      for(i=0;i<m;i++){
        printf("here\n");
        rc2 = pthread_join(subthreads[i], &subthreadstatus);
        if (rc2) {
          printf("ERROR; return code from pthread_join() is %d\n", rc2);
          exit(-1);
        }
      }
      */
      /*this works because the way code is written, if it 
      makes it here all connections have been made*/
      //printf("all pubs and subs have connected to server\n");
      for(i = 0; i<n+m; i++){
        printf("Type:%s, ID: %d, Topic: %s\n", record[i].type, record[i].pid, record[i].selectTopics);
      }
      //begin termination

      write(ServerFD[1], terminate, strlen(terminate));
      close(ServerFD[1]);
      for(i = 0; i<n+m; i++){
        printf("%s-%d: terminated\n", record[i].type,record[i].pid);
      }
      //printf("%s\n", );
      pthread_exit(NULL);

	
}
	else
		wait(&status);
		//main process just needs to wait for everything else to be done.


	return(0);
}
Example #11
0
int main(void)
{
	signal(SIGCHLD, SigchldHandler);
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == sockfd) {
		perror("Socket error:\n");
		return -1;
	}
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(SERVER_PORT);
	addr.sin_addr.s_addr = inet_addr(SERVER_IP);
	int optval = 1;
	if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
		perror("Set socket option error:\n");
	}
	if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))) {
		perror("Bind error:\n");
		return -1;
	}
	if (-1 == listen(sockfd, SOMAXCONN)) {
		perror("Listen error:\n");
		return -1;
	}
	while (1) {
		struct sockaddr_in clientaddr;
		socklen_t socklen = sizeof(clientaddr);
		int connfd = accept(sockfd, (struct sockaddr *)&clientaddr, &socklen);
		pid_t pid = fork();
		if (-1 == pid) {
			perror("Create process error:\n");
			exit(-1);	
		}
		else if (0 == pid) { //child process
			if (-1 == connfd) {
				perror("Accept error:\n");
				return -1;
			}
			printf("child process.\n");
			printf("client address %s.\n", inet_ntoa(clientaddr.sin_addr));
			while (1) {
				char recbuffer[1024] = {0};
				int readlen = read(connfd, recbuffer, sizeof(recbuffer));	
				if (-1 == readlen) {
					if (EINTR == errno) {
						continue;
					}
					//return - 1;
					exit(-1);
				}
				else if (0 == readlen) {
					printf("Client close.\n");
					close(connfd);
					exit(0);
				}
				else {
//					if (recbuffer[0] == 'c') {
//						close(connfd);
//						exit(0);
//					}
					printf("recv %s.\n", recbuffer);
					int writelen = write(connfd, recbuffer, strlen(recbuffer));
					if (-1 == writelen) {
						if (EINTR == errno) {
							continue;
						}
						close(connfd);
						//shutdown(connfd, SHUT_RDWR);
						exit(-1);
					}
					else if (writelen > 0) {
						//TODO something
					}
					else {
					}
					memset(recbuffer, 0, sizeof(recbuffer));
				}
			}
		}
		else if (pid > 0) { //parent process
			close(connfd);
		}
	}
	return 0;
}
Example #12
0
void copylink(char *source, char *dest, int mode, int owner, int group)
{
	struct stat sst, dst;
	int sfd, dfd, n;
	int r, same= 0, change= 0, docopy= 1;
	char buf[4096];
#	define hdr ((struct exec *) buf)
	pid_t pid;
	int status;

	/* Source must exist as a plain file, dest may exist as a plain file. */

	if (stat(source, &sst) < 0) { report(source); return; }

	if (mode == -1) {
		mode= sst.st_mode & 07777;
		if (!lflag || cflag) {
			mode|= 0444;
			if (mode & 0111) mode|= 0111;
		}
	}
	if (owner == -1) owner= sst.st_uid;
	if (group == -1) group= sst.st_gid;

	if (!S_ISREG(sst.st_mode)) {
		fprintf(stderr, "install: %s is not a regular file\n", source);
		excode= 1;
		return;
	}
	r= stat(dest, &dst);
	if (r < 0) {
		if (errno != ENOENT) { report(dest); return; }
	} else {
		if (!S_ISREG(dst.st_mode)) {
			fprintf(stderr, "install: %s is not a regular file\n",
									dest);
			excode= 1;
			return;
		}

		/* Are the files the same? */
		if (sst.st_dev == dst.st_dev && sst.st_ino == dst.st_ino) {
			if (!lflag && cflag) {
				fprintf(stderr,
				"install: %s and %s are the same, can't copy\n",
					source, dest);
				excode= 1;
				return;
			}
			same= 1;
		}
	}

	if (lflag && !same) {
		/* Try to link the files. */

		if (r >= 0 && unlink(dest) < 0) {
			report(dest); return;
		}

		if (link(source, dest) >= 0) {
			docopy= 0;
		} else {
			if (!cflag || errno != EXDEV) {
				fprintf(stderr,
					"install: can't link %s to %s: %s\n",
					source, dest, strerror(errno));
				excode= 1;
				return;
			}
		}
	}

	if (docopy && !same) {
		/* Copy the files, stripping if necessary. */
		long count= LONG_MAX;
		int first= 1;

		if ((sfd= open(source, O_RDONLY)) < 0) {
			report(source); return;
		}

		/* Open for write is less simple, its mode may be 444. */
		dfd= open(dest, O_WRONLY|O_CREAT|O_TRUNC, mode | 0600);
		if (dfd < 0 && errno == EACCES) {
			(void) chmod(dest, mode | 0600);
			dfd= open(dest, O_WRONLY|O_TRUNC);
		}
		if (dfd < 0) {
			report(dest);
			close(sfd);
			return;
		}

		pid= 0;
		while (count > 0 && (n= read(sfd, buf, sizeof(buf))) > 0) {
			if (first && n >= A_MINHDR && !BADMAG(*hdr)) {
				if (strip) {
					count= hdr->a_hdrlen
						+ hdr->a_text + hdr->a_data;
#ifdef A_NSYM
					hdr->a_flags &= ~A_NSYM;
#endif
					hdr->a_syms= 0;
				}
				if (stack != -1 && setstack(hdr)) change= 1;

				if (compress != nil) {
					/* Write first #! line. */
					(void) write(dfd, zcat, strlen(zcat));

					/* Put a compressor in between. */
					if ((pid= filter(dfd, compress)) < 0) {
						close(sfd);
						close(dfd);
						return;
					}
					change= 1;
				}
			}
			if (count < n) n= count;

			if (write(dfd, buf, n) < 0) {
				report(dest);
				close(sfd);
				close(dfd);
				if (pid != 0) (void) waitpid(pid, nil, 0);
				return;
			}
			count-= n;
			first= 0;
		}
		if (n < 0) report(source);
		close(sfd);
		close(dfd);
		if (pid != 0 && waitpid(pid, &status, 0) < 0 || status != 0) {
			excode= 1;
			return;
		}
		if (n < 0) return;
	} else {
		if (stack != -1) {
			/* The file has been linked into place.  Set the
			 * stack size.
			 */
			if ((dfd= open(dest, O_RDWR)) < 0) {
				report(dest);
				return;
			}

			if ((n= read(dfd, buf, sizeof(*hdr))) < 0) {
				report(dest); return;
			}

			if (n >= A_MINHDR && !BADMAG(*hdr) && setstack(hdr)) {
				if (lseek(dfd, (off_t) 0, SEEK_SET) == -1
					|| write(dfd, buf, n) < 0
				) {
					report(dest);
					close(dfd);
					return;
				}
				change= 1;
			}
			close(dfd);
		}
	}

	if (stat(dest, &dst) < 0) { report(dest); return; }

	if ((dst.st_mode & 07777) != mode) {
		if (chmod(dest, mode) < 0) { report(dest); return; }
	}
	if (dst.st_uid != owner || dst.st_gid != group) {
		if (chown(dest, owner, group) < 0 && errno != EPERM) {
			report(dest); return;
		}
		/* Set the mode again, chown may have wrecked it. */
		(void) chmod(dest, mode);
	}
	if (!change) {
		struct utimbuf ubuf;

		ubuf.actime= dst.st_atime;
		ubuf.modtime= sst.st_mtime;

		if (utime(dest, &ubuf) < 0 && errno != EPERM) {
			report(dest); return;
		}
	}
}
Example #13
0
static int __write_to_log_daemon(log_id_t log_id, struct iovec *vec, size_t nr)
{
    ssize_t ret;
#if FAKE_LOG_DEVICE
    int log_fd;

    if (/*(int)log_id >= 0 &&*/ (int)log_id < (int)LOG_ID_MAX) {
        log_fd = log_fds[(int)log_id];
    } else {
        return -EBADF;
    }
    do {
        ret = fakeLogWritev(log_fd, vec, nr);
        if (ret < 0) {
            ret = -errno;
        }
    } while (ret == -EINTR);
#else
    static const unsigned header_length = 2;
    struct iovec newVec[nr + header_length];
    android_log_header_t header;
    android_pmsg_log_header_t pmsg_header;
    struct timespec ts;
    size_t i, payload_size;
    static uid_t last_uid = AID_ROOT; /* logd *always* starts up as AID_ROOT */
    static pid_t last_pid = (pid_t) -1;
    static atomic_int_fast32_t dropped;

    if (!nr) {
        return -EINVAL;
    }

    if (last_uid == AID_ROOT) { /* have we called to get the UID yet? */
        last_uid = getuid();
    }
    if (last_pid == (pid_t) -1) {
        last_pid = getpid();
    }
    /*
     *  struct {
     *      // what we provide to pstore
     *      android_pmsg_log_header_t pmsg_header;
     *      // what we provide to socket
     *      android_log_header_t header;
     *      // caller provides
     *      union {
     *          struct {
     *              char     prio;
     *              char     payload[];
     *          } string;
     *          struct {
     *              uint32_t tag
     *              char     payload[];
     *          } binary;
     *      };
     *  };
     */

    clock_gettime(CLOCK_REALTIME, &ts);

    pmsg_header.magic = LOGGER_MAGIC;
    pmsg_header.len = sizeof(pmsg_header) + sizeof(header);
    pmsg_header.uid = last_uid;
    pmsg_header.pid = last_pid;

    header.tid = gettid();
    header.realtime.tv_sec = ts.tv_sec;
    header.realtime.tv_nsec = ts.tv_nsec;

    newVec[0].iov_base   = (unsigned char *) &pmsg_header;
    newVec[0].iov_len    = sizeof(pmsg_header);
    newVec[1].iov_base   = (unsigned char *) &header;
    newVec[1].iov_len    = sizeof(header);

    if (logd_fd > 0) {
        int32_t snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed);
        if (snapshot) {
            android_log_event_int_t buffer;

            header.id = LOG_ID_EVENTS;
            buffer.header.tag = htole32(LIBLOG_LOG_TAG);
            buffer.payload.type = EVENT_TYPE_INT;
            buffer.payload.data = htole32(snapshot);

            newVec[2].iov_base = &buffer;
            newVec[2].iov_len  = sizeof(buffer);

            ret = TEMP_FAILURE_RETRY(writev(logd_fd, newVec + 1, 2));
            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
                atomic_fetch_add_explicit(&dropped, snapshot, memory_order_relaxed);
            }
        }
    }

    header.id = log_id;

    for (payload_size = 0, i = header_length; i < nr + header_length; i++) {
        newVec[i].iov_base = vec[i - header_length].iov_base;
        payload_size += newVec[i].iov_len = vec[i - header_length].iov_len;

        if (payload_size > LOGGER_ENTRY_MAX_PAYLOAD) {
            newVec[i].iov_len -= payload_size - LOGGER_ENTRY_MAX_PAYLOAD;
            if (newVec[i].iov_len) {
                ++i;
            }
            payload_size = LOGGER_ENTRY_MAX_PAYLOAD;
            break;
        }
    }
    pmsg_header.len += payload_size;

    if (pstore_fd >= 0) {
        TEMP_FAILURE_RETRY(writev(pstore_fd, newVec, i));
    }

    if (last_uid == AID_LOGD) { /* logd, after initialization and priv drop */
        /*
         * ignore log messages we send to ourself (logd).
         * Such log messages are often generated by libraries we depend on
         * which use standard Android logging.
         */
        return 0;
    }

    if (logd_fd < 0) {
        return -EBADF;
    }

    /*
     * The write below could be lost, but will never block.
     *
     * To logd, we drop the pmsg_header
     *
     * ENOTCONN occurs if logd dies.
     * EAGAIN occurs if logd is overloaded.
     */
    ret = TEMP_FAILURE_RETRY(writev(logd_fd, newVec + 1, i - 1));
    if (ret < 0) {
        ret = -errno;
        if (ret == -ENOTCONN) {
#if !defined(_WIN32)
            pthread_mutex_lock(&log_init_lock);
#endif
            close(logd_fd);
            logd_fd = -1;
            ret = __write_to_log_initialize();
#if !defined(_WIN32)
            pthread_mutex_unlock(&log_init_lock);
#endif

            if (ret < 0) {
                return ret;
            }

            ret = TEMP_FAILURE_RETRY(writev(logd_fd, newVec + 1, i - 1));
            if (ret < 0) {
                ret = -errno;
            }
        }
    }

    if (ret > (ssize_t)sizeof(header)) {
        ret -= sizeof(header);
    } else if (ret == -EAGAIN) {
        atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed);
    }
#endif

    return ret;
}
Example #14
0
void SocketTransport::rejectClientWithMsg(int newFd, int abortFd) {
  VSDebugLogger::Log(
    VSDebugLogger::LogLevelInfo,
    "SocketTransport: new client connection rejected because another "
      "client is already connected."
  );

  folly::dynamic rejectMsg = folly::dynamic::object;
  rejectMsg["category"] = OutputLevelError;
  rejectMsg["output"] = "Could not attach to HHVM: another debugger "
    "client is already attached!";

  folly::dynamic response = folly::dynamic::object;
  response["event"] = EventTypeOutput;
  response["body"] = rejectMsg;
  response["type"] = MessageTypeEvent;

  // Send the user an error message.
  std::string serialized =  folly::toJson(response);
  const char* output = serialized.c_str();
  write(newFd, output, strlen(output) + 1);

  // Perform an orderly shutdown of the socket so that the message is actually
  // sent and received. This requires us to shutdown the write end of the socket
  // and then drain the receive buffer before closing the socket. If abortFd
  // is signalled before this is complete, we just close the socket and bail.
  ::shutdown(newFd, SHUT_WR);

  int result;
  size_t size = sizeof(struct pollfd) * 2;
  struct pollfd* fds = (struct pollfd*)malloc(size);
  char* buffer = (char*)malloc(1024);
  SCOPE_EXIT {
    if (fds != nullptr) {
      free(fds);
    }

    close(newFd);

    if (buffer != nullptr) {
      free(buffer);
    }
  };

  if (buffer == nullptr || fds == nullptr) {
    return;
  }

  int eventMask = POLLIN | POLLERR | POLLHUP;
  constexpr int abortIdx = 0;
  constexpr int readIdx = 1;

  memset(fds, 0, size);
  fds[abortIdx].fd = abortFd;
  fds[abortIdx].events = eventMask;
  fds[readIdx].fd = newFd;
  fds[readIdx].events = eventMask;

  while (true) {
    result = poll(fds, 2, -1);
    if (result == -EINTR) {
      continue;
    } else if (result < 0 ||
               fds[abortIdx].revents != 0 ||
               fds[readIdx].revents & POLLERR ||
               fds[readIdx].revents & POLLHUP
               ) {

      break;
    } else if (fds[readIdx].revents & POLLIN) {
      result = read(newFd, buffer, 1024);
      if (result <= 0) {
        break;
      }
    }
  }
}
Example #15
0
/* Execute a script, wait for termination and return its stdout.
 * script_name IN - Name of program being run (e.g. "StartStageIn")
 * script_path IN - Fully qualified program of the program to execute
 * script_args IN - Arguments to the script
 * max_wait IN - Maximum time to wait in milliseconds,
 *		 -1 for no limit (asynchronous)
 * data_in IN - data to use as program STDIN (NULL if not STDIN)
 * status OUT - Job exit code
 * Return stdout+stderr of spawned program, value must be xfreed. */
extern char *power_run_script(char *script_name, char *script_path,
			      char **script_argv, int max_wait, char *data_in,
			      int *status)
{
	int i, new_wait, resp_size = 0, resp_offset = 0;
	int send_size = 0, send_offset = 0;
	pid_t cpid;
	char *resp = NULL;
	int fd_stdout[2] = { -1, -1 };
	int fd_stdin[2] = { -1, -1 };

	if ((script_path == NULL) || (script_path[0] == '\0')) {
		error("%s: no script specified", __func__);
		*status = 127;
		resp = xstrdup("Slurm burst buffer configuration error");
		return resp;
	}
	if (slurm_get_debug_flags() & DEBUG_FLAG_POWER) {
		for (i = 0; i < 10; i++) {
			if (!script_argv[i])
				break;
		}
		if (i == 0) {
			info("%s:", __func__);
		} else if (i == 1) {
			info("%s: %s", __func__, script_name);
		} else if (i == 2) {
			info("%s: %s %s", __func__, script_name,
			     script_argv[1]);
		} else if (i == 3) {
			info("%s: %s %s %s", __func__, script_name,
			     script_argv[1], script_argv[2]);
		} else if (i == 4) {
			info("%s: %s %s %s %s", __func__, script_name,
			     script_argv[1], script_argv[2], script_argv[3]);
		} else if (i == 5) {
			info("%s: %s %s %s %s %s", __func__, script_name,
			     script_argv[1], script_argv[2], script_argv[3],
			     script_argv[4]);
		} else if (i == 6) {
			info("%s: %s %s %s %s %s %s", __func__, script_name,
			     script_argv[1], script_argv[2], script_argv[3],
			     script_argv[4], script_argv[5]);
		} else if (i == 7) {
			info("%s: %s %s %s %s %s %s %s", __func__,
			     script_name, script_argv[1], script_argv[2],
			     script_argv[3], script_argv[4], script_argv[5],
			     script_argv[6]);
		} else {	/* 8 or more args here, truncate as needed */
			info("%s: %s %s %s %s %s %s %s %s", __func__,
			     script_name, script_argv[1], script_argv[2],
			     script_argv[3], script_argv[4], script_argv[5],
			     script_argv[6], script_argv[7]);
		}
		if (data_in)
			info("%s: %s", __func__, data_in);
	}
	if (script_path[0] != '/') {
		error("%s: %s is not fully qualified pathname (%s)",
		      __func__, script_name, script_path);
		*status = 127;
		resp = xstrdup("Slurm burst buffer configuration error");
		return resp;
	}
	if (access(script_path, R_OK | X_OK) < 0) {
		error("%s: %s can not be executed (%s) %m",
		      __func__, script_name, script_path);
		*status = 127;
		resp = xstrdup("Slurm burst buffer configuration error");
		return resp;
	}
	if (data_in) {
		if (pipe(fd_stdin) != 0) {
			error("%s: pipe(): %m", __func__);
			*status = 127;
			resp = xstrdup("System error");
			return resp;
		}
	}
	if (max_wait != -1) {
		if (pipe(fd_stdout) != 0) {
			error("%s: pipe(): %m", __func__);
			*status = 127;
			resp = xstrdup("System error");
			return resp;
		}
	}
	if ((cpid = fork()) == 0) {
		int cc;

		cc = sysconf(_SC_OPEN_MAX);
		if (data_in)
			dup2(fd_stdin[0], STDIN_FILENO);
		if (max_wait != -1) {
			dup2(fd_stdout[1], STDERR_FILENO);
			dup2(fd_stdout[1], STDOUT_FILENO);
			for (i = 0; i < cc; i++) {
				if ((i != STDERR_FILENO) &&
				    (i != STDIN_FILENO)  &&
				    (i != STDOUT_FILENO))
					close(i);
			}
		} else {
			for (i = 0; i < cc; i++) {
				if (!data_in || (i != STDERR_FILENO))
					close(i);
			}
			if ((cpid = fork()) < 0)
				exit(127);
			else if (cpid > 0)
				exit(0);
		}
		setpgid(0, 0);
		execv(script_path, script_argv);
		error("%s: execv(%s): %m", __func__, script_path);
		exit(127);
	} else if (cpid < 0) {
		if (data_in) {
			close(fd_stdin[0]);
			close(fd_stdin[1]);
		}
		if (max_wait != -1) {
			close(fd_stdout[0]);
			close(fd_stdout[1]);
		}
		error("%s: fork(): %m", __func__);
	} else if (max_wait != -1) {
		struct pollfd fds;
		time_t start_time = time(NULL);
		if (data_in) {
			close(fd_stdin[0]);
			send_size = strlen(data_in);
			while (send_size > send_offset) {
				i = write(fd_stdin[1], data_in + send_offset,
					 send_size - send_offset);
				if (i == 0) {
					break;
				} else if (i < 0) {
					if (errno == EAGAIN)
						continue;
					error("%s: write(%s): %m", __func__,
					      script_path);
					break;
				} else {
					send_offset += i;
				}
			}
			close(fd_stdin[1]);
		}
		resp_size = 1024;
		resp = xmalloc(resp_size);
		close(fd_stdout[1]);
		while (1) {
			fds.fd = fd_stdout[0];
			fds.events = POLLIN | POLLHUP | POLLRDHUP;
			fds.revents = 0;
			if (max_wait <= 0) {
				new_wait = -1;
			} else {
				new_wait = (time(NULL) - start_time) * 1000
					   + max_wait;
				if (new_wait <= 0)
					break;
			}
			i = poll(&fds, 1, new_wait);
			if (i == 0) {
				error("%s: %s poll timeout",
				      __func__, script_name);
				break;
			} else if (i < 0) {
				error("%s: %s poll:%m", __func__, script_name);
				break;
			}
			if ((fds.revents & POLLIN) == 0)
				break;
			i = read(fd_stdout[0], resp + resp_offset,
				 resp_size - resp_offset);
			if (i == 0) {
				break;
			} else if (i < 0) {
				if (errno == EAGAIN)
					continue;
				error("%s: read(%s): %m", __func__,
				      script_path);
				break;
			} else {
				resp_offset += i;
				if (resp_offset + 1024 >= resp_size) {
					resp_size *= 2;
					resp = xrealloc(resp, resp_size);
				}
			}
		}
		killpg(cpid, SIGKILL);
		waitpid(cpid, status, 0);
		close(fd_stdout[0]);
	} else {
		waitpid(cpid, status, 0);
	}
	return resp;
}
Example #16
0
int main()
{
	socklen_t clt_addr_len;
	int listen_fd;
	int com_fd;
	int old_fd;
	int ret;
	int i;
	static char recv_buf[1024];	
	int len;

	struct sockaddr_un clt_addr;
	struct sockaddr_un srv_addr;

	listen_fd=socket(PF_UNIX,SOCK_STREAM,0);
	if(listen_fd<0){
		perror("cannot create listening socket");
		return 1;
	}

	srv_addr.sun_family=AF_UNIX;
	strncpy(srv_addr.sun_path,UNIX_DOMAIN,sizeof(srv_addr.sun_path)-1);
	unlink(UNIX_DOMAIN);

	ret=bind(listen_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
	if(ret==-1){
		perror("cannot bind server socket");
		close(listen_fd);
		unlink(UNIX_DOMAIN);
		return 1;
	}

	ret=listen(listen_fd,1);
	if(ret==-1){
		perror("cannot listen the client connect request");
		close(listen_fd);
		unlink(UNIX_DOMAIN);
		return 1;
	}
	
	len=sizeof(clt_addr);
	com_fd=accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
	if(com_fd<0){
		perror("cannot accept client connect request");
		close(listen_fd);
		unlink(UNIX_DOMAIN);
		return 1;	
	}
	
	printf("\n=====info=====\n");
	for(i=0;i<4;i++){
		memset(recv_buf,0,1024);
		int num=read(com_fd,recv_buf,sizeof(recv_buf));
		printf("Message from client (%d)) :%s\n",num,recv_buf);	
	}

	close(com_fd);
	close(listen_fd);
	
	unlink(UNIX_DOMAIN);
	return 0;
}
Example #17
0
/*
====================
IPSocket
====================
*/
static int IPSocket( const char *net_interface, int port, netadr_t *bound_to = NULL )
{
    int newsocket;
    struct sockaddr_in address;
    int i = 1;

    if ( net_interface )
    {
        common->Printf( "Opening IP socket: %s:%i\n", net_interface, port );
    }
    else
    {
        common->Printf( "Opening IP socket: localhost:%i\n", port );
    }

    if ( ( newsocket = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == -1 )
    {
        common->Printf( "ERROR: IPSocket: socket: %s", strerror( errno ) );
        return 0;
    }
    // make it non-blocking
    int on = 1;
    if ( ioctl( newsocket, FIONBIO, &on ) == -1 )
    {
        common->Printf( "ERROR: IPSocket: ioctl FIONBIO:%s\n",
                        strerror( errno ) );
        return 0;
    }
    // make it broadcast capable
    if ( setsockopt( newsocket, SOL_SOCKET, SO_BROADCAST, (char *) &i, sizeof(i) ) == -1 )
    {
        common->Printf( "ERROR: IPSocket: setsockopt SO_BROADCAST:%s\n", strerror( errno ) );
        return 0;
    }

    if ( !net_interface || !net_interface[ 0 ]
            || !idStr::Icmp( net_interface, "localhost" ) )
    {
        address.sin_addr.s_addr = INADDR_ANY;
    }
    else
    {
        StringToSockaddr( net_interface, &address, true );
    }

    if ( port == PORT_ANY )
    {
        address.sin_port = 0;
    }
    else
    {
        address.sin_port = htons((short) port);
    }

    address.sin_family = AF_INET;

    if ( bind( newsocket, (const struct sockaddr *)&address, sizeof( address ) ) == -1 )
    {
        common->Printf( "ERROR: IPSocket: bind: %s\n", strerror( errno ) );
        close( newsocket );
        return 0;
    }

    if ( bound_to )
    {
        unsigned int len = sizeof( address );
        if ( (unsigned int)(getsockname( newsocket, (struct sockaddr *)&address, (socklen_t*)&len )) == -1 )
        {
            common->Printf( "ERROR: IPSocket: getsockname: %s\n", strerror( errno ) );
            close( newsocket );
            return 0;
        }
        SockadrToNetadr( &address, bound_to );
    }

    return newsocket;
}
Example #18
0
static void *mpich1_thr(void *arg)
{
	int cc, flags;
	int new_port, new_fd;
	struct pollfd ufds[2];
	struct sockaddr cli_addr;
	socklen_t cli_len;
	char in_buf[128];
	debug("waiting for p4 communication");
	if ((flags = fcntl(p4_fd1, F_GETFL)) < 0) {
		error("mpich_p4: fcntl: %m");
		goto done;
	}
	if (fcntl(p4_fd1, F_SETFL, flags | O_NONBLOCK) < 0) {
		error("mpich_p4: fcntl: %m");
		goto done;
	}
	ufds[0].fd = p4_fd1;
	ufds[0].events = POLLIN;
	ufds[1].fd = shutdown_pipe[0];
	ufds[1].events = POLLIN;

	while (1) {
		if (p4_tid == (pthread_t) -1)
			goto done;
		cc = read(p4_fd1, &new_port, sizeof(new_port));
		if (cc >= 0)
			break;
		if (errno != EAGAIN) {
			error("mpich_p4: read/1: %m");
			goto done;
		}
		cc = poll(ufds, 2, 10000);
		if (cc <= 0) {
			error("mpich_p4: poll/1: %m");
			goto done;
		}
		if (ufds[1].revents & POLLIN) {
			goto done;
		}
	}
	if (cc != sizeof(new_port)) {
		error("mpich_p4: read/1 %d bytes", cc);
		goto done;
	}
	debug("mpich_p4 read/1 port %d", new_port);

	ufds[0].fd = p4_fd2;

	/* send this port number to other tasks on demand */
	while (1) {
		if (p4_tid == (pthread_t) -1)
			goto done;

		cc = poll(ufds, 2, -1);
		if (cc <= 0) {
			error("mpich_p4: poll/2: %m");
			goto done;
		}
		if (ufds[1].revents & POLLIN) {
			goto done;
		}

		new_fd = accept(p4_fd2, &cli_addr, &cli_len);
		if (new_fd < 0)
			continue;
		cc = read(new_fd, in_buf, sizeof(in_buf));
		if (cc > 0)
			debug("mpich_p4 read/2 port: %s", in_buf);
		cc = write(new_fd, &new_port, sizeof(new_port));
		if (cc < sizeof(new_port))
			error("mpich_p4: write2: %m");
		close(new_fd);
	}

done:
	pthread_mutex_lock(&shutdown_lock);
	shutdown_complete = true;
	pthread_cond_signal(&shutdown_cond);
	pthread_mutex_unlock(&shutdown_lock);
	return NULL;
}
Example #19
0
void SliderSettingsDialog::cancelButtonPressed()
{
  // close dialog, drop input
  close();
}
Example #20
0
int main(int argc, char *argv[]){
	int pid = 0;
	int children[5];
	int i = 0;
	int child = 0;
	int status;
	FILE *fp = NULL;
	int ch;
	int lines = 0;
	int words = 0;
	//char *file_name = "./word_10MB.txt";
	char *file_name = "./dllist.c";
	fp = fopen(file_name, "r");
	int iterator = 0;
	char string[1024];
	while(!feof(fp)){
		ch = fscanf(fp, '\n', string);
		printf(string);
	}
	int fd[2];
	pipe(fd);
	for(i = 0; i < 5; i++){
		pid = fork();
		if(pid != 0){
			children[i] = pid;
			waitpid(children[i], &status, 0);
		} else {
			child = 1;
			break;
		}
	}
	if(child == 0){
		close(fd[1]);
		printf("parent process, pid: %d\n", getpid());
		char buffer[80];
		int c = 0;
		for(i = 0; i < 5; i++){
			printf("child_pid: %d\n", children[i]);
		}
		do {
			c = read(fd[0], buffer, sizeof(buffer));
			printf("word: '%s'\n", buffer);
		} while(c > 0);
		/*do {
			c = fscanf(&fd[0], "%s", buffer);
			if(c != EOF){
				char *temp_word = buffer;
				printf("word: '%s'\n", temp_word);
			}
		} while(c != EOF);*/
	} else {
		close(fd[0]);
		char *test_insert[] = {"test1", "test2", "test3"};
		for(i = 0; i < 3; i++){
			write(fd[1], test_insert[i], (strlen(test_insert[i]) + 1));
		}
		printf("child process, pid: %d, ppid: %d\n", pid, getppid());
	}
	printf("%d\n", child);
	
	printf("file_name: %s, lines: %d, words: %d\n", file_name, lines, words);
	return 0;
}
Example #21
0
int
ssvm_master_init_shm (ssvm_private_t * ssvm)
{
  int ssvm_fd;
#if USE_DLMALLOC == 0
  int mh_flags = MHEAP_FLAG_DISABLE_VM | MHEAP_FLAG_THREAD_SAFE;
#endif
  clib_mem_vm_map_t mapa = { 0 };
  u8 junk = 0, *ssvm_filename;
  ssvm_shared_header_t *sh;
  uword page_size, requested_va = 0;
  void *oldheap;

  if (ssvm->ssvm_size == 0)
    return SSVM_API_ERROR_NO_SIZE;

  if (CLIB_DEBUG > 1)
    clib_warning ("[%d] creating segment '%s'", getpid (), ssvm->name);

  ASSERT (vec_c_string_is_terminated (ssvm->name));
  ssvm_filename = format (0, "/dev/shm/%s%c", ssvm->name, 0);
  unlink ((char *) ssvm_filename);
  vec_free (ssvm_filename);

  ssvm_fd = shm_open ((char *) ssvm->name, O_RDWR | O_CREAT | O_EXCL, 0777);
  if (ssvm_fd < 0)
    {
      clib_unix_warning ("create segment '%s'", ssvm->name);
      return SSVM_API_ERROR_CREATE_FAILURE;
    }

  if (fchmod (ssvm_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0)
    clib_unix_warning ("ssvm segment chmod");
  if (svm_get_root_rp ())
    {
      /* TODO: is this really needed? */
      svm_main_region_t *smr = svm_get_root_rp ()->data_base;
      if (fchown (ssvm_fd, smr->uid, smr->gid) < 0)
	clib_unix_warning ("ssvm segment chown");
    }

  if (lseek (ssvm_fd, ssvm->ssvm_size, SEEK_SET) < 0)
    {
      clib_unix_warning ("lseek");
      close (ssvm_fd);
      return SSVM_API_ERROR_SET_SIZE;
    }

  if (write (ssvm_fd, &junk, 1) != 1)
    {
      clib_unix_warning ("set ssvm size");
      close (ssvm_fd);
      return SSVM_API_ERROR_SET_SIZE;
    }

  page_size = clib_mem_get_fd_page_size (ssvm_fd);
  if (ssvm->requested_va)
    {
      requested_va = ssvm->requested_va;
      clib_mem_vm_randomize_va (&requested_va, min_log2 (page_size));
    }

  mapa.requested_va = requested_va;
  mapa.size = ssvm->ssvm_size;
  mapa.fd = ssvm_fd;
  if (clib_mem_vm_ext_map (&mapa))
    {
      clib_unix_warning ("mmap");
      close (ssvm_fd);
      return SSVM_API_ERROR_MMAP;
    }
  close (ssvm_fd);

  sh = mapa.addr;
  sh->master_pid = ssvm->my_pid;
  sh->ssvm_size = ssvm->ssvm_size;
  sh->ssvm_va = pointer_to_uword (sh);
  sh->type = SSVM_SEGMENT_SHM;
#if USE_DLMALLOC == 0
  sh->heap = mheap_alloc_with_flags (((u8 *) sh) + page_size,
				     ssvm->ssvm_size - page_size, mh_flags);
#else
  sh->heap = create_mspace_with_base (((u8 *) sh) + page_size,
				      ssvm->ssvm_size - page_size,
				      1 /* locked */ );
  mspace_disable_expand (sh->heap);
#endif

  oldheap = ssvm_push_heap (sh);
  sh->name = format (0, "%s", ssvm->name, 0);
  ssvm_pop_heap (oldheap);

  ssvm->sh = sh;
  ssvm->my_pid = getpid ();
  ssvm->i_am_master = 1;

  /* The application has to set set sh->ready... */
  return 0;
}
Example #22
0
DirectResult
voodoo_play_get_broadcast( VoodooPlayAddress **ret_addr,
                           size_t             *ret_num )
{
    size_t             num = 0;
    size_t             i   = 0;
    VoodooPlayAddress *addr;

    int            ret;
    int            fd;
    char          *ptr, lastname[IFNAMSIZ];
    struct ifreq   req[16];
    struct ifconf  conf;

    D_ASSERT( ret_addr != NULL );
    D_ASSERT( ret_num != NULL );

    conf.ifc_buf = (char*) req;
    conf.ifc_len = sizeof(req);

    fd = socket( AF_INET, SOCK_DGRAM, 0 );
    if (fd < 0) {
        D_PERROR( "Voodoo/Unix: socket( AF_INET, SOCK_DGRAM, 0 ) failed!\n" );
        return DR_FAILURE;
    }

    ret = ioctl( fd, SIOCGIFCONF, &conf );
    if (ret) {
        D_PERROR( "Voodoo/Player: ioctl( SIOCGIFCONF ) failed!\n" );
        close( fd );
        return DR_FAILURE;
    }

    lastname[0] = 0;

    for (ptr = conf.ifc_buf; ptr < conf.ifc_buf + conf.ifc_len; ) {
        struct ifreq         ifrcopy, *ifr  = (struct ifreq *)ptr;
        struct sockaddr_in  *saddr = (struct sockaddr_in*) &ifr->ifr_broadaddr;

#ifdef MACOS
        ptr += sizeof(ifr->ifr_name) + MAX(sizeof(struct sockaddr), ifr->ifr_addr.sa_len); // for next one in buffer
#else
        ptr += sizeof(req[0]);
#endif

        if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) {
            continue; /* already processed this interface */
        }

        memcpy(lastname, ifr->ifr_name, IFNAMSIZ);

        ifrcopy = *ifr;
        ioctl( fd, SIOCGIFFLAGS, &ifrcopy);
        if ((ifrcopy.ifr_flags & IFF_UP) == 0)
            continue;   // ignore if interface not up

        ret = ioctl( fd, SIOCGIFBRDADDR, ifr );
        if (ret)
            continue;

        if (!saddr->sin_addr.s_addr) {
            ret = ioctl( fd, SIOCGIFDSTADDR, ifr );
            if (ret)
                continue;
        }

        num++;
    }


    addr = D_CALLOC( num, sizeof(VoodooPlayAddress) );
    if (!addr) {
        close( fd );
        return D_OOM();
    }


    for (ptr = conf.ifc_buf; ptr < conf.ifc_buf + conf.ifc_len; ) {
        char                 buf[100];
        struct ifreq         ifrcopy, *ifr  = (struct ifreq *)ptr;
        struct sockaddr_in  *saddr = (struct sockaddr_in*) &ifr->ifr_broadaddr;

#ifdef MACOS
        ptr += sizeof(ifr->ifr_name) + MAX(sizeof(struct sockaddr), ifr->ifr_addr.sa_len); // for next one in buffer
#else
        ptr += sizeof(req[0]);
#endif

        if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) {
            continue; /* already processed this interface */
        }

        memcpy(lastname, ifr->ifr_name, IFNAMSIZ);

        ifrcopy = *ifr;
        ioctl( fd, SIOCGIFFLAGS, &ifrcopy);
        if ((ifrcopy.ifr_flags & IFF_UP) == 0) {
            D_INFO( "Voodoo/Player:   %-16s is not up.\n", ifrcopy.ifr_name );
            continue;   // ignore if interface not up
        }

        ret = ioctl( fd, SIOCGIFBRDADDR, ifr );
        if (ret) {
            D_PERROR( "Voodoo/Player: ioctl( SIOCGIFBRDADDR ) %-16s failed!\n", ifr->ifr_name );
            continue;
        }

        if (saddr->sin_addr.s_addr) {
            inet_ntop( AF_INET, &saddr->sin_addr, buf, sizeof(buf) );

            D_INFO( "Voodoo/Player:   %-16s (%s)\n", ifr->ifr_name, buf );
        }
        else {
            ret = ioctl( fd, SIOCGIFDSTADDR, ifr );
            if (ret) {
                D_PERROR( "Voodoo/Player: ioctl( SIOCGIFDSTADDR ) failed!\n" );
                continue;
            }

            inet_ntop( AF_INET, &saddr->sin_addr, buf, sizeof(buf) );

            D_INFO( "Voodoo/Player:   %-16s (%s) (P-t-P)\n", ifr->ifr_name, buf );
        }

        voodoo_play_from_inet_addr( &addr[i++], saddr->sin_addr.s_addr );
    }

    close( fd );

    *ret_addr = addr;
    *ret_num  = num;

    return DR_OK;
}
Example #23
0
int main(int argc, char *argv[])
{
    int sockfd, newsockfd, portno, clilen;
    struct sockaddr_in serv_addr, cli_addr;
    struct sigaction old_sigint, new_sigint;
    struct sigaction old_sigchld, new_sigchld;

    /* sets up the dump for when ctrl+c is hit */
    sigset_t set;
    new_sigint.sa_handler = exit_dump;
    new_sigint.sa_flags = 0;
    new_sigint.sa_mask = set;
    sigaction(SIGINT, &new_sigint, &old_sigint);

    /* sets up handling SIGCHLD */
    sigset_t set2;
    new_sigchld.sa_handler = handle_sigchld;
    new_sigchld.sa_flags = SA_RESTART;
    new_sigchld.sa_mask = set2;
    sigaction(SIGCHLD, &new_sigchld, &old_sigchld);

    if(argc < 2)
    {
        fprintf(stderr, "ERROR, no port provided\n");
        exit(1);
    }

    /* creates the socket sockfd using the internet, TCP,
     * and default protocol */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0) error("ERROR opening socket");

    /* fills serv_addr with 0's */
    bzero((char *)&serv_addr, sizeof(serv_addr));

    /* converts the port number argument to an int */
    portno = atoi(argv[1]);

    /* protocol = internet */
    serv_addr.sin_family = AF_INET;
    /* accept any IP address */
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    /* ensure the information from port portno has the right endian-ness */
    serv_addr.sin_port = htons(portno);

    /* binds the port we're going to listen on to the socket */
    if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        error("ERROR on binding");

    printf("I am the personality test server and my pid number is %d\n", getpid());

    /* wait for connection, give it to the socket, accept up to 5 */
    listen(sockfd, 5);
    clilen = sizeof(cli_addr);

    /* infinite loop of peace, love, and acceptance */
    while(1)
    {
        /* accepts a connection to a client so we can get info */
        newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
        if(newsockfd < 0) error("ERROR on accept");

        int childpid = fork();
        if(childpid == -1) error("ERROR forking off a new child");
        if(childpid == 0)
        {
            /* deals with the connection to client */
            handle_connection(newsockfd);
            exit(0);
        } else {
            printf("A connection! My child #%d will take care of it\n", childpid);
            close(newsockfd);
        }
    }
    return 0;
}
Example #24
0
/** @main Application entry-point. */
int main(int argc, char* argv[])
{
    int c;
    strcpy(initcmd, DEF_CMD_INIT);
    while (true)
    {
        static struct option long_options[] =
        {
            {"adapter", required_argument, 0, 'a'},
            {"remote-adapter", required_argument, 0, 'b'},
            {"close", no_argument, 0, 'c'},
            {"blink-on-receive", no_argument, 0, 'k'},
            {"log-packets", no_argument, 0, 'p'},
            {"verbose", no_argument, 0, 'v'},
            {"version", no_argument, 0, 'V'},
            {"help", no_argument, 0, 'h'},
            {0, 0, 0, 0}
        };
        /* getopt_long stores the option index here. */
        int option_index = 0;
        c = getopt_long (argc, argv, "a:b:ckpvV?", long_options, &option_index);
        
        /* Detect the end of the options. */
        if (c == -1)
            break;
        switch (c) {
            case 'a':
                tc_eth_adapter = optarg;
                break;
            case 'b':
                tc_eth_remoteAdapter = optarg;
                break;
            case 'c':
                exitReason = 0;
                break;
            case 'p':
                dbg_logPackets = true;
                break;
            case 'v':
                dbg_debugOut = true;
                break;
            case 'k':
                dbg_blinkOnReceive = true;
                break;
            case 'V':
                printf("Asus-TCCI (TrendChip Command Interpreter), version %s, build %s\n", VERSION, VERSION_BUILD);
                printf(" by %s. Sources and updates: %s\n", AUTHOR, URL);
                return EC_NORMAL;
            case 'h':
                /* getopt_long already printed an error message. */
                printf("usage: %s -V|--version\n", argv[0]); 
                printf("or: %s [-a|--adapter=\"%s\"] [-b|--remote-adapter=\"%s\"] [-c|--close] [-p|--log-packets] [-v|--verbose] [-k|--blink-on-receive] [<%s>]\n", argv[0], tc_eth_adapter, tc_eth_remoteAdapter, initcmd);
                
                return EC_NORMAL;
            default:
                return 9;
        }
    }
    
    /* Print any remaining command line arguments (not options). */
    if (optind < argc) {
        initcmd[0] = '\0'; // Clear string
        while (optind < argc)
            strncat(initcmd, argv[optind++], sizeof(initcmd));
    }
    debugf("-- Starting...\n");
    // Initialize in-socket
    tc_eth_sockIn = socket(AF_INET, SOCK_DGRAM, 0);
    if (tc_eth_sockIn < 0)
    {
        errorf("-- E: Input socket init failed!\n");
        return EC_APIFAIL;
    }
	/*debugf("-- dbg_debugOut = %d, dbg_logPackets = %d, tc_eth_adapter = \"%s\", initcmd = \"%s\"\n",
	    dbg_debugOut, dbg_logPackets, tc_eth_adapter, initcmd);*/
	// Initialize adapter
	eth_adapterId = if_nametoindex(tc_eth_adapter);
    initAdapter(tc_eth_adapter);
    // Initialize out-socket
    tc_eth_sockOut = socket(AF_PACKET,SOCK_RAW, htons(ETH_P_ALL));
    if (tc_eth_sockOut < 0)
    {
        errorf("-- E: Output socket init failed!\n");
        return EC_APIFAIL;
    }
    // Acquired MACs
    debugf("Remote (TrendChip) MAC: ");
    printmac(debugf, tc_eth_remoteMac);
    debugf("\nLocal (terminal) MAC: ");
    printmac(debugf, tc_eth_localMac);
    // Initial command execution
    debugf("\n-- Phase 2 - Perform init-command (%s)\n", initcmd);
    if (!tc_exec(initcmd))
        return EC_NETFAIL;
    // Interactive shell
    char inbuff[TC_CMD_MAX_LEN];
    fd_set rfds;
    struct timeval tv;
    int retval;
    while(exitReason < 0) {
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);
        tv.tv_sec = 0;
        tv.tv_usec = 100000; //100ms
        retval = select(1, &rfds, NULL, NULL, &tv);
        if (retval == -1){
            perror("-- select(stdin)");
            return EC_APIFAIL;
        }
        else if (retval){   
            debugf("-- Gathering input... "); 
            char* cmd = fgets(inbuff, TC_CMD_MAX_LEN, stdin);
            if (cmd[strlen(cmd)-1] == '\n')
                cmd[strlen(cmd)-1] = '\0'; // Trim the trailing '\n' char.
            debugf("Got '%s'\n", cmd); 
            if (cmd[0] == '\0')
                {} // Do nothing on blank lines.
            else if (strcmp(cmd, "!q") == 0 || strcmp(cmd, "!quit") == 0)
                exitReason = EC_NORMAL;
            else if (strcmp(cmd, "!v") == 0 || strcmp(cmd, "!verbose") == 0)
                errorf("-- Verbose output is now %s.\n", (dbg_debugOut = !dbg_debugOut) ? "ON" : "OFF");
            else if (strcmp(cmd, "!p") == 0 || strcmp(cmd, "!logpackets") == 0)
                errorf("-- Packet logging is now %s.\n", (dbg_logPackets = !dbg_logPackets) ? "ON" : "OFF");
            else if (strcmp(cmd, "!k") == 0 || strcmp(cmd, "!blink") == 0)
                errorf("-- Blink-on-receive is now %s.\n", (dbg_blinkOnReceive = !dbg_blinkOnReceive) ? "ON" : "OFF");
            else if (strcmp(cmd, "!h") == 0 || strcmp(cmd, "!help") == 0)
                errorf("-- Valid client commands: \n--  ![blin]k, !h[elp], ![log]p[ackets], !q[uit], !v[erbose].\n"); 
            else if (cmd[0] == '!')
                errorf("-- Unrecognized client command. Please try \"!help\" if you aren't sure.\n"); 
            else if (!tc_exec(cmd))
                errorf("-- W: Command request fail!\n");
                //exitReason = EC_NETFAIL; // I/O error?
        }
        if (!tc_listen())
            exitReason = EC_NETFAIL;
    }
    if (tc_eth_sockIn) 
        close(tc_eth_sockIn);
    else
        debugf("-- W: Input socket already closed!");
    if (tc_eth_sockOut) 
        close(tc_eth_sockOut);
    else
        debugf("-- W: Output socket already closed!");
    debugf("-- Connection closed, reason = %d (-1).\n", exitReason);
    return exitReason-1;
}
Example #25
0
void CloseComport(int comport_number)
{
    close(Cport[comport_number]);
    tcsetattr(Cport[comport_number], TCSANOW, old_port_settings + comport_number);
}
Example #26
0
	// Shamelessly stolen from PCVideoServer
	int DashboardCommandServer()
	{
	    /* Setup to PC sockets */
	    struct sockaddr_in serverAddr;
	    int sockAddrSize = sizeof(serverAddr);
	    int pcSock = ERROR;
	    bzero ((char *) &serverAddr, sockAddrSize);
	    serverAddr.sin_len = (u_char) sockAddrSize;
	    serverAddr.sin_family = AF_INET;
	    serverAddr.sin_port = htons (kDashboardCommandPort);
	    serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);

	    while (true)
	    {
	        taskSafe();
	    	  //  Create the socket.
	        if ((pcSock = socket (AF_INET, SOCK_STREAM, 0)) == ERROR)
	        {
	            perror ("socket");
	            continue;
	        }
	        //  Set the TCP socket so that it can be reused if it is in the wait state.
	        int reuseAddr = 1;
	        setsockopt(pcSock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&reuseAddr), sizeof(reuseAddr));
	        //  Bind socket to local address.
	        if (bind (pcSock, (struct sockaddr *) &serverAddr, sockAddrSize) == ERROR)
	        {
	            perror ("bind");
	            close (pcSock);
	            continue;
	        }
	        //  Create queue for client connection requests.
	        if (listen (pcSock, 1) == ERROR)
	        {
	            perror ("listen");
	            close (pcSock);
	            continue;
	        }

	        struct sockaddr_in clientAddr;
	        int clientAddrSize;
	        int newPCSock = accept (pcSock, reinterpret_cast<sockaddr*>(&clientAddr), &clientAddrSize);
	        if (newPCSock  == ERROR)
	        {
	            close(pcSock);
	            continue;
	        }

	        char cmdBuffer[32];
	        char *pBuffer;
	        while(1)
	        {
	            int numBytes = 0;
	            pBuffer = cmdBuffer;
	            while (numBytes < 2 || (*(pBuffer-2) != '\r' && *(pBuffer-1) != '\n'))
	            {
		            numBytes += read(newPCSock, pBuffer++, 1);
	            }
	            char command = cmdBuffer[0];
	            switch (command)
	            {
	            case 'E':
	            	speedJag.EnableControl();
	            	//printf("Enable\n");
	            	break;
	            case 'D':
	            	speedJag.DisableControl();
	            	//printf("Disable\n");
	            	break;
	            case 'G':
	            	{
	            		double P, I, D;
	            		memcpy((char*)&P, cmdBuffer+1, sizeof(double));
	            		memcpy((char*)&I, cmdBuffer+9, sizeof(double));
	            		memcpy((char*)&D, cmdBuffer+17, sizeof(double));
	            		speedJag.SetPID(P, I, D);
	            		//printf("Set- P: %f I: %f D: %f\n", P, I, D);
	            		//P = speedJag.GetP();
	            		//I = speedJag.GetI();
	            		//D = speedJag.GetD();
	            		//printf("Get- P: %f I: %f D: %f\n", P, I, D);
	            	}
	            	break;
	            }

	            //no point in running too fast -
	            Wait(0.01);
	        }
	        //  Clean up
	        close (newPCSock);
	        newPCSock = ERROR;
	        close (pcSock);
	        pcSock = ERROR;
	        taskUnsafe();
	        Wait(0.1);
	    }
	    return (OK);
	}
Example #27
0
int send_pack(struct send_pack_args *args,
	      int fd[], struct child_process *conn,
	      struct ref *remote_refs,
	      struct sha1_array *extra_have)
{
	int in = fd[0];
	int out = fd[1];
	struct strbuf req_buf = STRBUF_INIT;
	struct strbuf cap_buf = STRBUF_INIT;
	struct ref *ref;
	int need_pack_data = 0;
	int allow_deleting_refs = 0;
	int status_report = 0;
	int use_sideband = 0;
	int quiet_supported = 0;
	int agent_supported = 0;
	int use_atomic = 0;
	int atomic_supported = 0;
	unsigned cmds_sent = 0;
	int ret;
	struct async demux;
	const char *push_cert_nonce = NULL;

	git_config(send_pack_config, NULL);

	/* Does the other end support the reporting? */
	if (server_supports("report-status"))
		status_report = 1;
	if (server_supports("delete-refs"))
		allow_deleting_refs = 1;
	if (server_supports("ofs-delta"))
		args->use_ofs_delta = 1;
	if (config_use_sideband && server_supports("side-band-64k"))
		use_sideband = 1;
	if (server_supports("quiet"))
		quiet_supported = 1;
	if (server_supports("agent"))
		agent_supported = 1;
	if (server_supports("no-thin"))
		args->use_thin_pack = 0;
	if (server_supports("atomic"))
		atomic_supported = 1;
	if (args->push_cert) {
		int len;

		push_cert_nonce = server_feature_value("push-cert", &len);
		if (!push_cert_nonce)
			die(_("the receiving end does not support --signed push"));
		reject_invalid_nonce(push_cert_nonce, len);
		push_cert_nonce = xmemdupz(push_cert_nonce, len);
	}

	if (!remote_refs) {
		fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
			"Perhaps you should specify a branch such as 'master'.\n");
		return 0;
	}
	if (args->atomic && !atomic_supported)
		die(_("the receiving end does not support --atomic push"));

	use_atomic = atomic_supported && args->atomic;

	if (status_report)
		strbuf_addstr(&cap_buf, " report-status");
	if (use_sideband)
		strbuf_addstr(&cap_buf, " side-band-64k");
	if (quiet_supported && (args->quiet || !args->progress))
		strbuf_addstr(&cap_buf, " quiet");
	if (use_atomic)
		strbuf_addstr(&cap_buf, " atomic");
	if (agent_supported)
		strbuf_addf(&cap_buf, " agent=%s", git_user_agent_sanitized());

	/*
	 * NEEDSWORK: why does delete-refs have to be so specific to
	 * send-pack machinery that set_ref_status_for_push() cannot
	 * set this bit for us???
	 */
	for (ref = remote_refs; ref; ref = ref->next)
		if (ref->deletion && !allow_deleting_refs)
			ref->status = REF_STATUS_REJECT_NODELETE;

	if (!args->dry_run)
		advertise_shallow_grafts_buf(&req_buf);

	if (!args->dry_run && args->push_cert)
		cmds_sent = generate_push_cert(&req_buf, remote_refs, args,
					       cap_buf.buf, push_cert_nonce);

	/*
	 * Clear the status for each ref and see if we need to send
	 * the pack data.
	 */
	for (ref = remote_refs; ref; ref = ref->next) {
		switch (check_to_send_update(ref, args)) {
		case 0: /* no error */
			break;
		case CHECK_REF_STATUS_REJECTED:
			/*
			 * When we know the server would reject a ref update if
			 * we were to send it and we're trying to send the refs
			 * atomically, abort the whole operation.
			 */
			if (use_atomic)
				return atomic_push_failure(args, remote_refs, ref);
			/* Fallthrough for non atomic case. */
		default:
			continue;
		}
		if (!ref->deletion)
			need_pack_data = 1;

		if (args->dry_run || !status_report)
			ref->status = REF_STATUS_OK;
		else
			ref->status = REF_STATUS_EXPECTING_REPORT;
	}

	/*
	 * Finally, tell the other end!
	 */
	for (ref = remote_refs; ref; ref = ref->next) {
		char *old_hex, *new_hex;

		if (args->dry_run || args->push_cert)
			continue;

		if (check_to_send_update(ref, args) < 0)
			continue;

		old_hex = sha1_to_hex(ref->old_sha1);
		new_hex = sha1_to_hex(ref->new_sha1);
		if (!cmds_sent) {
			packet_buf_write(&req_buf,
					 "%s %s %s%c%s",
					 old_hex, new_hex, ref->name, 0,
					 cap_buf.buf);
			cmds_sent = 1;
		} else {
			packet_buf_write(&req_buf, "%s %s %s",
					 old_hex, new_hex, ref->name);
		}
	}

	if (args->stateless_rpc) {
		if (!args->dry_run && (cmds_sent || is_repository_shallow())) {
			packet_buf_flush(&req_buf);
			send_sideband(out, -1, req_buf.buf, req_buf.len, LARGE_PACKET_MAX);
		}
	} else {
		write_or_die(out, req_buf.buf, req_buf.len);
		packet_flush(out);
	}
	strbuf_release(&req_buf);
	strbuf_release(&cap_buf);

	if (use_sideband && cmds_sent) {
		memset(&demux, 0, sizeof(demux));
		demux.proc = sideband_demux;
		demux.data = fd;
		demux.out = -1;
		if (start_async(&demux))
			die("send-pack: unable to fork off sideband demultiplexer");
		in = demux.out;
	}

	if (need_pack_data && cmds_sent) {
		if (pack_objects(out, remote_refs, extra_have, args) < 0) {
			for (ref = remote_refs; ref; ref = ref->next)
				ref->status = REF_STATUS_NONE;
			if (args->stateless_rpc)
				close(out);
			if (git_connection_is_socket(conn))
				shutdown(fd[0], SHUT_WR);
			if (use_sideband)
				finish_async(&demux);
			fd[1] = -1;
			return -1;
		}
		if (!args->stateless_rpc)
			/* Closed by pack_objects() via start_command() */
			fd[1] = -1;
	}
	if (args->stateless_rpc && cmds_sent)
		packet_flush(out);

	if (status_report && cmds_sent)
		ret = receive_status(in, remote_refs);
	else
		ret = 0;
	if (args->stateless_rpc)
		packet_flush(out);

	if (use_sideband && cmds_sent) {
		if (finish_async(&demux)) {
			error("error in sideband demultiplexer");
			ret = -1;
		}
		close(demux.out);
	}

	if (ret < 0)
		return ret;

	if (args->porcelain)
		return 0;

	for (ref = remote_refs; ref; ref = ref->next) {
		switch (ref->status) {
		case REF_STATUS_NONE:
		case REF_STATUS_UPTODATE:
		case REF_STATUS_OK:
			break;
		default:
			return -1;
		}
	}
	return 0;
}
Example #28
0
int main(int argc, char *argv[]) {
   int fd1, fd2, verify_fd1;
   char *file_1 = "test1.txt";
   char *file_2 = "test2.txt";

   umask(0);
   if ((fd1 = open(file_1, O_CREAT, RWRWRW)) < 0) {
      fprintf(stderr, "Err. create file\n");
      exit(EXIT_FAILURE);
   }
 
   umask(022);
   if ((fd2 = open(file_2, O_CREAT, RWRWRW)) < 0) {
      fprintf(stderr, "Err. create file\n");
      exit(EXIT_FAILURE);
   }
/*
HEADER: <unistd.h>
PROTOTIPO: int access(const char *pathname, int mode);
SEMANTICA: verifica i permessi di accesso 'mode' rispetto a 'pathname'.
RITORNA: 0 in caso di successo, -1 in caso di errore.
 
access() permette di verificare l'accesso ad un file, controllando i permessi
relativi al real-User-ID e al real-Group-ID; da notare che di solito, quando
si apre un file, il kernel verifica l'accesso controllando l'effective-User-ID
e l'effective-Group-ID.

Le costanti simboliche utilizzabili da 'mode' sono:
- F_OK = test di esistenza del file;
- R_OK = test di lettura del file;
- W_OK = test di scrittura del file;
- X_OK = test di esecuzione del file.

Gli ultimi 3 sono eseguiti solo se la prima e' vera.
*/
   /* Verifica del file */
   if ((verify_fd1 = access(file_1, F_OK)) < 0) {
      fprintf(stderr, "Il file '%s' non esiste \n", file_1);
      exit(EXIT_FAILURE);
   }

   /* Accesso lettura r */
   if ((verify_fd1 = access(file_1, R_OK)) < 0) {
      fprintf(stderr, "Il file '%s' non e' leggibile \n", file_1);
      exit(EXIT_FAILURE);
   } else
      fprintf(stdout, "Il file '%s'  e' leggibile \n", file_1);

   /* Accesso scrittura w */
   if ((verify_fd1 = access(file_1, W_OK)) < 0) {
      fprintf(stderr, "Il file '%s' non e' scrivibile \n", file_1);
      exit(EXIT_FAILURE);
   } else
      fprintf(stdout, "Il file '%s'  e' scriviibile \n", file_1);

   /* Accesso esecuzione  x */
   if ((verify_fd1 = access(file_1, X_OK)) < 0) {
      fprintf(stderr, "Il file '%s' non e' eseguibile \n", file_1);
      exit(EXIT_FAILURE);
   } else
      fprintf(stdout, "Il file '%s'  e' eseguiibile \n", file_1);

   close(fd1);
   close(fd2);

   return(EXIT_SUCCESS);
}
Example #29
0
/* Initialize the /dev/fbN device for a specific screen */
static int pvrQwsInitFbScreen(int screen)
{
    struct fb_var_screeninfo var;
    struct fb_fix_screeninfo fix;
    unsigned long start;
    unsigned long length;
    int width, height, stride;
    PVR2DFORMAT format;
    void *mapped;
    int fd, bytesPerPixel;
    char name[64];
    PVR2DMEMINFO *memInfo;
    unsigned long pageAddresses[2];

    /* Bail out if already initialized, or the number is incorrect */
    if (screen < 0 || screen >= PVRQWS_MAX_SCREENS)
        return 0;
    if (pvrQwsDisplay.screens[screen].initialized)
        return 1;

    /* Open the framebuffer and fetch its properties */
    sprintf(name, "/dev/fb%d", screen);
    fd = open(name, O_RDWR, 0);
    if (fd < 0) {
        perror(name);
        return 0;
    }
    if (ioctl(fd, FBIOGET_VSCREENINFO, &var) < 0) {
        perror("FBIOGET_VSCREENINFO");
        close(fd);
        return 0;
    }
    if (ioctl(fd, FBIOGET_FSCREENINFO, &fix) < 0) {
        perror("FBIOGET_FSCREENINFO");
        close(fd);
        return 0;
    }
    width = var.xres;
    height = var.yres;
    bytesPerPixel = var.bits_per_pixel / 8;
    stride = fix.line_length;
    format = PVR2D_1BPP;
    if (var.bits_per_pixel == 16) {
        if (var.red.length == 5 && var.green.length == 6 &&
            var.blue.length == 5 && var.red.offset == 11 &&
            var.green.offset == 5 && var.blue.offset == 0) {
            format = PVR2D_RGB565;
        }
        if (var.red.length == 4 && var.green.length == 4 &&
            var.blue.length == 4 && var.transp.length == 4 &&
            var.red.offset == 8 && var.green.offset == 4 &&
            var.blue.offset == 0 && var.transp.offset == 12) {
            format = PVR2D_ARGB4444;
        }
    } else if (var.bits_per_pixel == 32) {
        if (var.red.length == 8 && var.green.length == 8 &&
            var.blue.length == 8 && var.transp.length == 8 &&
            var.red.offset == 16 && var.green.offset == 8 &&
            var.blue.offset == 0 && var.transp.offset == 24) {
            format = PVR2D_ARGB8888;
        }
    }
    if (format == PVR2D_1BPP) {
        fprintf(stderr, "%s: could not find a suitable PVR2D pixel format\n", name);
        close(fd);
        return 0;
    }
    start = fix.smem_start;
    length = var.xres_virtual * var.yres_virtual * bytesPerPixel;

    if (screen == 0) {
        /* We use PVR2DGetFrameBuffer to map the first screen.
           On some chipsets it is more reliable than using PVR2DMemWrap */
        mapped = 0;
        memInfo = 0;
    } else {
        /* Other screens: map the framebuffer region into memory */
        mapped = mmap(0, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (!mapped || mapped == (void *)(-1)) {
            perror("mmap");
            close(fd);
            return 0;
        }

        /* Allocate a PVR2D memory region for the framebuffer */
        memInfo = 0;
        if (pvrQwsDisplay.context) {
            pageAddresses[0] = start & 0xFFFFF000;
            pageAddresses[1] = 0;
            if (PVR2DMemWrap
                    (pvrQwsDisplay.context, mapped, PVR2D_WRAPFLAG_CONTIGUOUS,
                     length, pageAddresses, &memInfo) != PVR2D_OK) {
                munmap(mapped, length);
                close(fd);
                return 0;
            }
        }
    }

    /* We don't need the file descriptor any more */
    close(fd);

    /* The framebuffer is ready, so initialize the PvrQwsScreenInfo */
    pvrQwsDisplay.screens[screen].screenRect.x = 0;
    pvrQwsDisplay.screens[screen].screenRect.y = 0;
    pvrQwsDisplay.screens[screen].screenRect.width = width;
    pvrQwsDisplay.screens[screen].screenRect.height = height;
    pvrQwsDisplay.screens[screen].screenStride = stride;
    pvrQwsDisplay.screens[screen].pixelFormat = format;
    pvrQwsDisplay.screens[screen].bytesPerPixel = bytesPerPixel;
    pvrQwsDisplay.screens[screen].screenDrawable = 0;
    if (mapped) {
        /* Don't set these fields if mapped is 0, because PVR2DGetFrameBuffer
           may have already been called and set them */
        pvrQwsDisplay.screens[screen].frameBuffer = memInfo;
        pvrQwsDisplay.screens[screen].mapped = mapped;
    }
    pvrQwsDisplay.screens[screen].mappedLength = length;
    pvrQwsDisplay.screens[screen].screenStart = start;
    pvrQwsDisplay.screens[screen].needsUnmap = (mapped != 0);
    pvrQwsDisplay.screens[screen].initialized = 1;
    return 1;
}
Example #30
0
int
main(int argc, char *argv[])
{
	int i, maxfd, nready, str_len;
	fd_set global_rfds, current_rfds;


	char buf[BUF_SIZE];
	struct timeval timeout;

	struct sockaddr_in cli_addr;
	socklen_t socklen;
	int socket_fd, connect_fd;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <port>\n", argv[0]);
		exit(EXIT_FAILURE);
	}


	socket_fd = create_socket(argv[1]);
	if (socket_fd == -1) {
		fprintf(stderr, "create_socket() failed.\n");
		exit(EXIT_FAILURE);
	}

	// 初始化select
	maxfd = socket_fd;

	FD_ZERO(&global_rfds);		//清空
	FD_SET(socket_fd, &global_rfds);	//将监听socket加入select检测的描述符集合

	printf("FD_SETSIZE = %d\n", FD_SETSIZE);

	socklen = sizeof(cli_addr);
	while (1) {

		// 等待5.5秒
		timeout.tv_sec = 5;	/* seconds */
		timeout.tv_usec = 500 * 1000;	/* microseconds 微秒 */

		current_rfds = global_rfds;

		nready = select(maxfd + 1, &current_rfds, NULL, NULL, &timeout);
		if (nready == -1) {
			fprintf(stderr, "select() failed\n");
			break;
		} else if (nready == 0) {
			printf("time out!\n");
			continue;
		}

		// 这种方式不太好
		for (i = 0; i < maxfd + 1; ++i) {
			if (FD_ISSET(i, &current_rfds)) {
				if (i == socket_fd) {
					// new client connection
					connect_fd = accept(socket_fd,
						(struct sockaddr *) &cli_addr,
						&socklen);
					FD_SET(connect_fd, &global_rfds);
					if (connect_fd > maxfd)
						maxfd = connect_fd;
					printf("new client connected\n");
				} else {
					// read msg
					str_len = read(i, buf, sizeof(buf));
					if (str_len <= 0) {
						// client closed
						FD_CLR(i, &global_rfds);
						close(i);
						printf("client closed\n");
					} else {
						// echo
						write(i, buf, str_len);
					}
				}
			}
		}
	}
	close(socket_fd);

	return 0;
}