当前位置: 首页>>代码示例>>C++>>正文


C++ close函数代码示例

本文整理汇总了C++中close函数的典型用法代码示例。如果您正苦于以下问题:C++ close函数的具体用法?C++ close怎么用?C++ close使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了close函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: OpenComport

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);
//.........这里部分代码省略.........
开发者ID:microdevicer,项目名称:meteoboard-project,代码行数:101,代码来源:rs232.c

示例2: pack_objects

/*
 * 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;
}
开发者ID:houzhenggang,项目名称:git,代码行数:80,代码来源:send-pack.c

示例3: main

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 ;
}
开发者ID:LaughingSun,项目名称:nanocomm,代码行数:72,代码来源:nanocomm.cpp

示例4: main

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;
}
开发者ID:RayPlante,项目名称:usvirtualobservatory,代码行数:69,代码来源:anyauthput.c

示例5: main

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;
}
开发者ID:djmitche,项目名称:gnulib,代码行数:88,代码来源:test-remove.c

示例6: main

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", 
//.........这里部分代码省略.........
开发者ID:AlexShiLucky,项目名称:demo,代码行数:101,代码来源:epoll01.c

示例7: main


//.........这里部分代码省略.........
          //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);
}
开发者ID:mmaurice,项目名称:UOProjects,代码行数:101,代码来源:DIServer.c

示例8: main

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;
}
开发者ID:MingYueRuYa,项目名称:cprimeprimecode,代码行数:85,代码来源:echoserver.c

示例9: copylink

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;
//.........这里部分代码省略.........
开发者ID:Edwin-Edward,项目名称:elks,代码行数:101,代码来源:install.c

示例10: __write_to_log_daemon


//.........这里部分代码省略.........
    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;
}
开发者ID:luckyan315,项目名称:jsbinder,代码行数:101,代码来源:logd_write.c

示例11: error


//.........这里部分代码省略.........
		*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) {
开发者ID:HPCNow,项目名称:slurm,代码行数:67,代码来源:power_common.c

示例12: main

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;
}
开发者ID:1023xp,项目名称:training,代码行数:62,代码来源:p13.2.c

示例13: IPSocket

/*
====================
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;
}
开发者ID:revelator,项目名称:Revelator-Doom3,代码行数:82,代码来源:posix_net.cpp

示例14: debug

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;
}
开发者ID:IFCA,项目名称:slurm,代码行数:82,代码来源:mpich1_p4.c

示例15: close

void SliderSettingsDialog::cancelButtonPressed()
{
  // close dialog, drop input
  close();
}
开发者ID:jonasfoe,项目名称:COPASI,代码行数:5,代码来源:SliderSettingsDialog.cpp


注:本文中的close函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。