Example #1
0
int 
main()
{
    int fd;
    fd=open("txt",O_RDWR | O_CREAT);
    char s[]="first write";
    if(fd==-1)
        printf("open error\n");
    if(write(fd,s,sizeof(s))<0)
    {
        close(fd);
        printf("first write error\n");
    }
    if(write(fd,"second write",13)<0){
        close(fd);
        printf("second write error\n");
    }
    set_fl(fd,O_APPEND);

    if(write(fd,"third write",12)<0){
        close(fd);
        printf("third write error\n");
    }
     
    printf("sdfsadf\n");
    close(fd);
}
int main(void)
{
    int ntowrite, nwrite;
    char *ptr;

    ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
    fprintf(stderr, "read %d bytes\n", ntowrite);

    set_fl(STDOUT_FILENO, O_NONBLOCK);  /* set nonblocking */

    ptr = buf;
    while (ntowrite > 0) {
        errno = 0;
        nwrite = write(STDOUT_FILENO, ptr, ntowrite);
        fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);

        if (nwrite > 0) {
            ptr += nwrite;
            ntowrite -= nwrite;
        }
    }

    clr_fl(STDOUT_FILENO, O_NONBLOCK);   /* clear nonblocking */

    exit(0);
}
int main(void)
{
     int        ntowrite = 0;
     int        nwrite = 0;
     char       *ptr = NULL;

     ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
     fprintf(stderr, "reawd %d bytes\n", ntowrite);

     set_fl(STDOUT_FILENO, O_NONBLOCK);     //设置为非阻塞

     ptr = buf;

     while(ntowrite > 0)
     {
          errno = 0;
          nwrite = write(STDOUT_FILENO, ptr, ntowrite);
          fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);

          if (nwrite > 0)
          {
              ptr += nwrite;
              ntowrite -= nwrite;
          }
     }

     clr_fl(STDOUT_FILENO, O_NONBLOCK);     //清除

     exit(0);
}
void fcntlTestGETFL_SETFL() {
    int fd = open("/tmp/a.txt", O_RDWR | O_APPEND);
    if (-1 == fd) {
        perror("open error");
    }
    // get file status
    int val;
    if ((val = fcntl(fd, F_GETFL, 0)) < 0)
        perror("fcntl F_GETFL error");
    if (val & O_APPEND)
        printf("append\n");
    if (val & O_NONBLOCK)
        printf("nonblock\n");

    set_fl(fd, O_NONBLOCK);		// set O_NONBLOCK
    clr_fl(fd, O_APPEND);		// clear O_APPEND

    // get file status now
    if ((val = fcntl(fd, F_GETFL, 0)) < 0)
        perror("fcntl F_GETFL error");
    printf("after set O_NONBLOCK and clear O_APPEND\n");
    if (val & O_APPEND)
        printf("append\n");
    if (val & O_NONBLOCK)
        printf("nonblock\n");
}
Example #5
0
void LightSettings::saveConfig()
{
    // safe call, always one selected.
    powerTypeChanged( b->powerSource->currentIndex() );

    // Set settings for current power source
    if ( powerStatus.wallStatus() == QPowerStatus::Available )
        currentMode = &externalMode;
    else
        currentMode = &batteryMode;
    
    QSettings cfg("Trolltech","qpe");
    cfg.beginGroup("LockPower");
    writeMode(cfg, &lockMode);
    cfg.endGroup();
    cfg.beginGroup("BatteryPower");
    writeMode(cfg, &batteryMode);
    cfg.endGroup();
    cfg.beginGroup("ExternalPower");
    writeMode(cfg, &externalMode);
    cfg.sync();

    int i_dim =      (currentMode->dim ? currentMode->intervalDim : 0);
    int i_lightoff = (currentMode->lightoff ? currentMode->intervalLightOff : 0);
    int i_suspend =  (currentMode->suspend ? currentMode->intervalSuspend : 0);

    set_fl(currentMode->brightness);

    QtopiaServiceRequest e("QtopiaPowerManager", "setIntervals(int,int,int)" );
    e << i_dim << i_lightoff << i_suspend;
    e.send();
}
Example #6
0
int
main(int argc, char *argv[])
{
	int				fd;
	pid_t			pid;
	char			buf[5];
	struct stat		statbuf;

	if (argc != 2) {
		fprintf(stderr, "usage: %s filename\n", argv[0]);
		exit(1);
	}
	if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0)
		err_sys("open error");
	if (write(fd, "abcdef", 6) != 6)
		err_sys("write error");

	/* turn on set-group-ID and turn off group-execute */
	if (fstat(fd, &statbuf) < 0)
		err_sys("fstat error");
	if (fchmod(fd, (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0)
		err_sys("fchmod error");

	TELL_WAIT();

	if ((pid = fork()) < 0) {
		err_sys("fork error");
	} else if (pid > 0) {	/* parent */
		/* write lock entire file */
		if (write_lock(fd, 0, SEEK_SET, 0) < 0)
			err_sys("write_lock error");

		TELL_CHILD(pid);

		if (waitpid(pid, NULL, 0) < 0)
			err_sys("waitpid error");
	} else {				/* child */
		WAIT_PARENT();		/* wait for parent to set lock */

		set_fl(fd, O_NONBLOCK);

		/* first let's see what error we get if region is locked */
		if (read_lock(fd, 0, SEEK_SET, 0) != -1)	/* no wait */
			err_sys("child: read_lock succeeded");
		printf("read_lock of already-locked region returns %d\n",
		  errno);

		/* now try to read the mandatory locked file */
		if (lseek(fd, 0, SEEK_SET) == -1)
			err_sys("lseek error");
		if (read(fd, buf, 2) < 0)
			err_ret("read failed (mandatory locking works)");
		else
			printf("read OK (no mandatory locking), buf = %2.2s\n",
			  buf);
	}
	exit(0);
}
int main(int argc,char ** argv)
{                     
    int                 fd;    
    pid_t               pid;   
    char                buf[5];
    struct stat         statbuf;                             
                           
    if(argc!=2)       
    {                 
        fprintf(stderr,"usage:%s filename \n",argv[0]);      
        exit(1);      
    }                 
    if((fd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,FILE_MODE))<0)
        err_sys("open error"); 
    if(write(fd,"abcdef",6)<0) 
        err_sys("write error");
                   
    if(fstat(fd,&statbuf)<0)   
        err_sys("fstat error");
    if(fchmod(fd,(statbuf.st_mode & ~S_IXGRP)|S_ISGID)<0)
        err_sys("fchmod error");
    TELL_WAIT();



    if((pid=fork())<0)
        err_sys("fork error");
    else if(pid>0)
    {
        if(write_lock(fd,0,SEEK_SET,0)<0)
            err_sys("write_lock error");
        TELL_CHILD(pid);
        if(waitpid(pid,NULL,0)<0)
            err_sys("waitpid error");
    }
    else 
    {
        WAIT_PARENT();
        set_fl(fd,O_NONBLOCK);

        if(read_lock(fd,0,SEEK_SET,0)!=-1)
            err_sys("child read_lock successed ");
        printf("read_lock of arleady-locked region return %d \n",errno);
        if(lseek(fd,0,SEEK_SET)==-1)
            err_sys("lseek error");
        if(read(fd,buf,2)<0)
            err_ret("read failed (mandatory locking works )");
        else 
            printf("read OK(no mandatory locking ,buf=%2.2s\n)",buf);
        exit(0);

    }
} 
Example #8
0
int main()
{
	int fd;
	int flags;
	if((fd = open("1.txt", O_RDONLY)) < 0)	
	{
		err_sys("open error\n");
	}
	
	flags = O_WRONLY;
	set_fl(fd, flags);
	return;
}
Example #9
0
int
socket_connect_nb(int sockfd, struct sockaddr *addr)
{
  int ret;

  set_fl(sockfd, O_NONBLOCK);
  errno = 0;
  ret = socket_connect(sockfd, addr);
  if (ret == -1) {
    switch(errno) {
    case EWOULDBLOCK:
      return -2;
    }
  }
  return ret;
}
Example #10
0
void LightSettings::applyBrightness()
{
    // slot called, but we haven't changed the powerMode values yet
    currentMode->brightness = b->brightness->value();
    set_fl(currentMode->brightness);

    QSettings config("Trolltech", "qpe");
    if (currentMode == &lockMode)
        config.beginGroup("LockPower");
    else if (currentMode == &batteryMode)
        config.beginGroup("BatteryPower");
    else
        config.beginGroup("ExternalPower");

    config.setValue("Brightness", (currentMode->brightness * 255 + qpe_sysBrightnessSteps()/2) / qpe_sysBrightnessSteps());
}
Example #11
0
int
main(void)
{
  int n;
  char buf[BUFSIZE];

  set_fl(STDOUT_FILENO, O_SYNC);

  if ( (n = read(STDIN_FILENO, buf, BUFSIZE)) < 0 )
    err_sys("read error");

  if (write(STDERR_FILENO, buf, n) != n)
    err_sys("write error");

  exit(0);
}
Example #12
0
File: pipe.c Project: geassdai/APUE
int main(){
    int i, n;
    int fd[2];

    if(pipe(fd) < 0)
        err_sys("pipe error");
    set_fl(fd[1], O_NONBLOCK);

    for(n = 0;; n++){
        if((i = write(fd[1], "a", 1)) != 1){
            printf("write ret %d, ", i);
            break;
        }
    }
    printf("pipe capacity = %d\n", n);
    exit(0);
}
Example #13
0
int main(void)
{
    int i, n;
    int fd[2];

    if (pipe(fd) < 0)
	err_sys("pipe error");
    set_fl(fd[1], O_NONBLOCK);

    /* write 1 byte at a time until pipe is full */
    for (n=0;;n++) {
	if ((i = write(fd[1], "a", 1)) != 1) {
	    printf("write ret %d, ", i);
	    break;
	}
    }
    printf("pipe capacity = %d\n", n);
    exit(0);
}
Example #14
0
/* get pipesize */
int main(void)
{
	int fd[2];
	int cnt;

	cnt = 0;
	Pipe(fd);
	set_fl(fd[1], O_NONBLOCK);

	fprintf(stderr, "PIPE_BUF: %d\n", PIPE_BUF);
	errno = 0;
	while(write(fd[1], "a", 1) != -1)
		cnt++;
	if (errno == EAGAIN)
		fprintf(stderr, "call would block (EAGAIN). cnt: %d)\n",cnt);
	else
		fprintf(stderr, "got another error: %d %s\n", errno, strerror(errno));
	return 0;
}
Example #15
0
static void transfer(const char *infile, const char *outfile) {
	int count;
	int rcount = 0;
	int wcount = 0;
	int flag = O_WRONLY | O_CREAT;

	//if (wrdisk)
	//	flag |= O_EXCL; // ensure not rewrite exist file
	
	if (infile && (infd = open(infile, O_RDONLY)) < 0) {
		err_sys("open '%s' error", infile);
	}

	assert(outfile != NULL);
	if (outfile && (outfd = open(outfile, flag,  S_IRUSR | S_IWUSR)) < 0) {
		err_sys("open '%s' error", outfile);
	}

	if (bSync)
		set_fl(outfd, O_SYNC);

	while ((count = read(infd, buf, bufSize)) > 0) {
		rcount += count;
		if (count != write(outfd, buf, count)){
			err_ret("write error");
			break;
		}	
		if (bFsync)
			fsync(outfd);

		if (bFdatasync)
			fdatasync(outfd);

		wcount += count;
	}
	if (count < 0)
		err_ret("read error");

	printf("r: %d, w: %d.\n", rcount, wcount);
}
Example #16
0
int main(int argc, char* argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <filename>\n", argv[1]);
    exit(1);
  }

  int fd;
  fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE);
  write(fd, "abcdef", 6);

  struct stat statbuf;
  fstat(fd, &statbuf);
  fchmod(fd, (statbuf.st_mode & ~S_IXGRP) | S_ISGID);

  tell_wait();

  pid_t pid;
  pid = fork();

  if (pid > 0) {
    write_lock(fd, 0, SEEK_SET, 0);
    tell_child(pid);
    waitpid(pid, NULL, 0);
  } else {
    wait_parent();
    set_fl(fd, O_NONBLOCK);

    if (read_lock(fd, 0, SEEK_SET, 0) != -1)
      err_sys("child: read_lock successed");
    printf("read_lock of already-locked region returns %d\n", errno);

    lseek(fd, 0, SEEK_SET);

    char buf[5];
    if (read(fd, buf, 2) < 0)
      err_ret("read failed (mandatory locking works)");
    else
      printf("read OK (no mandatory locking), buf = %2.2s\n", buf);
  }
}
Example #17
0
int main(void) {
    int ntowrite, nwrite;
    char *ptr;

    // 标准输入输出已打开,没必要open
    // 直接从标准输入读取数据(这里注意,遇到回车read将返回)
    ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
    fprintf(stderr, "read %d bytes\n", ntowrite);

    // 设置非阻塞
    set_fl(STDOUT_FILENO, O_NONBLOCK);
    ptr = buf;
    while (ntowrite > 0) {
        errno = 0;
        nwrite = write(STDOUT_FILENO, ptr, ntowrite);
        fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);
        if (nwrite > 0) {
            ptr += nwrite;
            ntowrite -= nwrite;
        }
    }
}
Example #18
0
File: 3-4.c Project: klion26/APUE
int main(int argc,char **argv)
{
	int val;
	if(2 != argc)
		err_quit("usage: a.out <descriptor#>");
	set_fl(STDOUT_FILENO,O_SYNC);
	if((val = fcntl(atoi(argv[1]),F_GETFL,0)) < 0)
		err_sys("fcntl error for fd %d",atoi(argv[1]));

	switch(val & O_ACCMODE)
		{
			case O_RDONLY:
				printf("read only");
				break;
			case O_WRONLY:
				printf("write only");
				break;
			case O_RDWR:
				printf("write read");
				break;
			default:
				err_dump("unknow access mode");
		}

	if(val & O_APPEND)
		printf(", append");
	if(val & O_NONBLOCK)
		printf(", nonblocking");
#if	defined(O_SYNC)
	if(val & O_SYNC)
		printf(", synchronous writes");
#endif
#if !defined(_POSIX_C_SOURCE) && defined(O_SFYNC)
	if(val & O_FSYNC)
		printf(", synchronous writes");
#endif
	putchar('\n');
	return 0;
}
Example #19
0
int main()
{
  int ntowrite, nwrite;
  char *ptr;
  ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
  fprintf(stderr, "прочитано %d байт\n", ntowrite);

  set_fl(STDOUT_FILENO, O_NONBLOCK);
  ptr = buf;
  while (ntowrite > 0) {
    errno = 0;
    nwrite = write(STDOUT_FILENO, ptr, ntowrite);
    fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);
    if (nwrite > 0) {
      ptr += nwrite;
      ntowrite = nwrite;
    }
  }
  clr_fl(STDOUT_FILENO, O_NONBLOCK);

  exit(0);
}
Example #20
0
int main()
{
    for(int i=0; i<500000; ++i) {
        buf[i] = 'a';
    }
    buf[499999] = 0;
    int ntowrite=499999, nwrite;
    char *ptr=buf;
    set_fl(STDOUT_FILENO, O_NONBLOCK);
    while(ntowrite>0) {
        errno = 0;
        nwrite = write(STDOUT_FILENO, ptr, ntowrite);
        fprintf(stderr, "nwrite = %d, errno = %d",nwrite, errno);
        if(errno!=0) perror("");
        else fprintf(stderr,"\n");
        if(nwrite>0) {
            ntowrite -= nwrite;
            ptr += nwrite;
        }
    }
    clr_fl(STDOUT_FILENO, O_NONBLOCK);
    return 0;
}
Example #21
0
int main(int argc, const char *argv[])
{
	int ntowrite, nwrite;
	char *ptr;

	ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
	fprintf(stderr, "read %d bytes\n", ntowrite);
	
	set_fl(STDOUT_FILENO, O_NONBLOCK);          /* set nonblocking */

	ptr = buf;
	while (ntowrite > 0) {
		errno = 0;
		nwrite = write(STDOUT_FILENO, ptr, ntowrite);
		fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);

		if (ntowrite > 0) {
			ptr += nwrite;
			ntowrite -= nwrite;
		}
	}
	return 0;
}
Example #22
0
int main() {
  int ntowrite, nwrite;
  char *ptr;
  ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
  fprintf(stderr, "read %d bytes\n", ntowrite);
  set_fl(STDOUT_FILENO, O_NONBLOCK);

  ptr = buf;
  while(ntowrite > 0) {
    errno = 0;
    nwrite = write(STDOUT_FILENO, ptr, ntowrite);
    fprintf(stderr,
            "nwrite = %d, errno = %s\n", nwrite, strerror(errno));

    if (nwrite > 0) {
      ptr += nwrite;
      ntowrite -= nwrite;
    }
  }

  clr_fl(STDOUT_FILENO, O_NONBLOCK);

  return 0;
}
Example #23
0
void LightSettings::reject()
{
    // Set settings for current power source
    if ( powerStatus.wallStatus() == QPowerStatus::Available )
        currentMode = &externalMode;
    else
        currentMode = &batteryMode;

    set_fl(currentMode->initBrightness);

    // Restore brightness settings
    QSettings config("Trolltech", "qpe");
    config.beginGroup("LockPower");
    config.setValue("Brightness", (batteryMode.initBrightness * 255 + qpe_sysBrightnessSteps()/2) / qpe_sysBrightnessSteps());
    config.endGroup();
    config.beginGroup("BatteryPower");
    config.setValue("Brightness", (batteryMode.initBrightness * 255 + qpe_sysBrightnessSteps()/2) / qpe_sysBrightnessSteps());
    config.endGroup();
    config.beginGroup("ExternalPower");
    config.setValue("Brightness", (externalMode.initBrightness * 255 + qpe_sysBrightnessSteps()/2) / qpe_sysBrightnessSteps());
    config.endGroup();

    QDialog::reject();
}
Example #24
0
static void process_list(DNODEPTR l_list)
{
   DNODEPTR  trav;

   char   child_buf[MAXHOST+1] = {0};
   char   dns_buf[MAXHOST+1] = {0};
   int    i;
   int    pid;
   int    nof_children = 0;
   fd_set rd_set;
  
   struct sigaction sigChildAction;
  
   sigChildAction.sa_handler = sigChild;
   sigChildAction.sa_flags   = SA_NOCLDSTOP|SA_RESTART;
   sigemptyset(&sigChildAction.sa_mask);

   raiseSigChild = 0;
  
   sigaction(SIGCHLD, &sigChildAction, NULL);
  
   /* fire up our child processes */
   for(i=0; i < dns_children; i++)
   {
      if(pipe(child[i].inpipe))
      {
         if (verbose) fprintf(stderr,"INPIPE creation error");
         return;   /* exit(1) */
      }

      if(pipe(child[i].outpipe))
      {
         if (verbose) fprintf(stderr,"OUTPIPE creation error");
         return;   /* exit(1); */
      }

      /* fork it off */
      switch(pid=fork())
      {
         case -1:
         {
            if (verbose) fprintf(stderr,"FORK error");
            return;  /* exit(1); */
         }
	  
         case 0:             /* Child */
         {
            int size;

            struct hostent *res_ent;

            close(child[i].inpipe[0]);
            close(child[i].outpipe[1]);

            /* get struct in_addr here */
            while((size = read(child[i].outpipe[0], child_buf, MAXHOST)))
            {
               if(size < 0)
               {
                  perror("read error");
                  exit(1);
               }
               else
               {
                  if(debug_mode)
                  printf("Child got work: %lx(%d)\n",
                          *((unsigned long *)child_buf), size);

                  if((res_ent = gethostbyaddr(child_buf, size, AF_INET)))
                  {
                     /* must be at least 4 chars */
                     if (strlen(res_ent->h_name)>3)
                     {
                        if(debug_mode)
                           printf("Child got %s for %lx(%d), %d bytes\n",
                                   res_ent->h_name,
                                   *((unsigned long *)child_buf),
                                   size,strlen(res_ent->h_name));

                        /* If long hostname, take max domain name part */
                        if ((size = strlen(res_ent->h_name)) > MAXHOST)
                           strcpy(child_buf,(res_ent->h_name+(size-MAXHOST)));
                        else strcpy(child_buf, res_ent->h_name);
                        size = strlen(child_buf);
                     }
                     else
                     {
                        if (debug_mode)
                           printf("gethostbyaddr returned bad h_name!\n");
                     }
                  }
                  else
                  {
                     if(debug_mode)
                        printf("gethostbyaddr returned NULL! (%d)\n",h_errno);
                  }

                  if (write(child[i].inpipe[1], child_buf, size) == -1)
                  {
                     perror("write error");
                     exit(1);
                  }
               }
            }
            close(child[i].inpipe[1]);
            close(child[i].outpipe[0]);
		
            if(debug_mode)
               printf( "Child %d got closed input, shutting down\n", i);  

            fflush(stdout);
            exit(0);
         }  /* case 0 */
		
         default:
         {
            child[i].pid = pid;
            child[i].flags = DNS_CHILD_READY|DNS_CHILD_RUNNING;
            nof_children++;
            close(child[i].inpipe[1]);
            close(child[i].outpipe[0]);

            set_fl(child[i].inpipe[0], O_NONBLOCK);
         }
      }
   }

   trav = l_list;

   while(nof_children)
   {
      static struct timeval selectTimeval;
      int res;
      int max_fd;
	  
      FD_ZERO(&rd_set);
      max_fd = 0;

      if(raiseSigChild)
      {
         int pid;

         while((pid = waitpid(-1, NULL, WNOHANG)) > 0)
         {
            for(i=0;i<dns_children;i++)
            {
               if(child[i].pid == pid)
               {
                  child[i].pid = 0;
                  child[i].flags &= ~(DNS_CHILD_READY|DNS_CHILD_RUNNING);
                  nof_children--;

                  if(debug_mode)
                  printf("Reaped Child %d\n", pid);

                  break;
               }
            }
         }
         raiseSigChild--;
         continue; /* while, nof children has just changed */
      }

      for(i=0;i<dns_children;i++)
      {
         if(child[i].flags & DNS_CHILD_RUNNING) /* Child is running */
         {
            if(child[i].flags & DNS_CHILD_READY)
            {
               child[i].flags  &= ~DNS_CHILD_READY;

               if(trav)  /* something to resolve */
               {
                  if (write(child[i].outpipe[1], &(trav->addr.s_addr),
                     sizeof(trav->addr.s_addr)) != -1)
                  {
                     /* We will watch this child */
                     child[i].cur    = trav;
                     FD_SET(child[i].inpipe[0], &rd_set);
                     max_fd = MAX(max_fd, child[i].inpipe[0]);

                     if(debug_mode)
                        printf("Giving %s (%lx) to Child %d for resolving\n",
                                child[i].cur->string,
                                (unsigned long)child[i].cur->addr.s_addr, i);

                     trav = trav->llist;
                  }
                  else  /* write error */
                  {
                     if(errno != EINTR)           /* Could be a signal */
                     {
                        perror("Could not write to pipe");
                        close(child[i].outpipe[1]);           /* kill     */
                        child[i].flags &= ~DNS_CHILD_RUNNING; /* child    */
                     }
		  }
               }
               else /* List is complete */
               {
                  close(child[i].outpipe[1]);            /* Go away       */
                  child[i].flags &= ~DNS_CHILD_RUNNING;  /* Child is dead */
               }
            }
            else
            {
               /* Look, the busy child... */
               FD_SET(child[i].inpipe[0], &rd_set);
               max_fd = MAX(max_fd, child[i].inpipe[0]);
            }
         }
      }

      selectTimeval.tv_sec =  5; /* This stuff ticks in 5 second intervals */
      selectTimeval.tv_usec = 0;

      switch(res = select(max_fd+1, &rd_set, NULL, NULL, &selectTimeval))
      {
         case -1:
         {
            if(errno != EINTR)   /* Could be a signal */
            perror("Error in select");

            break;
         }

         case 0:   /* Timeout, just fall once through the child loop */
         {
            if(debug_mode)
            printf("tick\n");
		
            break;
         }

         default:
         {
            for(i=0; i< dns_children;i++)
            {
               if(!res)   /* All file descriptors done */
               break;

               if(FD_ISSET(child[i].inpipe[0], &rd_set))
               {
                  int size;

                  res--;  /* One less... */

                  if(debug_mode)
                  printf("Work requested from Child %d\n", i);

                  switch (size=read(child[i].inpipe[0], dns_buf, MAXHOST))
                  {
                     case -1:
                     {
                        if(errno != EINTR)
                        perror("Could not read from pipe");
                        break;
                     }
                     case 0:
                     {
                        /* EOF. Child has closed Pipe. It shouldn't have */
                        /*  done that, could be an error or something.   */
                        /*  Reap it                                      */
                        close(child[i].outpipe[1]);
                        child[i].flags &= ~DNS_CHILD_RUNNING;

                        if(debug_mode)
                           printf("Child %d wants to be reaped\n", i);

                        break;
                     }

                     default:
                     {
                        dns_buf[size] = '\0';
                        if(memcmp(dns_buf, &(child[i].cur->addr.s_addr),
                                    sizeof(child[i].cur->addr.s_addr)))
                        {
                           if(debug_mode)
                              printf("Got a result (%d): %s -> %s\n",
                                     i, child[i].cur->string, dns_buf);
                           db_put(child[i].cur->string, dns_buf, 0);
                        }
                        else
                        {
                           if(debug_mode)
                              printf("Could not resolve (%d):  %s\n",
                                     i, child[i].cur->string); 
                           /*
                           db_put(child[i].cur->string,child[i].cur->string,1);
                           */
                        }

                        if(debug_mode)
                           printf("Child %d back in task pool\n", i);

                        /* Child is back in the task pool */
                        child[i].flags |= DNS_CHILD_READY;
                        break;
                     }
                  }
               }
            }
            break;
         }
      }
   }
   return;
}
Example #25
0
void set_nonblock(int fd)
{
    set_fl(fd, O_NONBLOCK);
}
Example #26
0
int do_loop(void) {
    int efd;
    int sfd;
    int rc;
    int connfd;
    struct epoll_event event;
    struct epoll_event *events;

    tor_array_t *cache_sock;
    cache_sock = tor_array_new(TOR_MAX_EVENT, sizeof(http_context *));

    events = calloc(TOR_MAX_EVENT, sizeof(struct epoll_event));
    if (!events) {
        perror("");
        exit(EXIT_FAILURE);
    }


    rc = 0;
    sfd = create_and_bind(INADDR_ANY, config.port);
    if (sfd < 0) {
        exit(EXIT_FAILURE);
    }

    rc = set_fl(sfd, O_NONBLOCK);
    if (rc < 0) {
        exit(EXIT_FAILURE);
    }

    rc = listen(sfd, 10);
    if (rc < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    efd = epoll_create1(0);
    if (efd < 0) {
        perror("");
        exit(EXIT_FAILURE);
    }

    if (fd_add(efd, sfd) < 0)
        exit(EXIT_FAILURE);

    int i, n;
    http_context *http;
    for (;;) {
        n = epoll_wait(efd, events, TOR_MAX_EVENT, -1);
        for (i = 0; i < n; i++) {

            if ((events[i].events & EPOLLERR) || 
                    (events[i].events & EPOLLHUP) ||
                    !(events[i].events & EPOLLIN)) {
                close(events[i].data.fd);
                tor_log_err("epoll error %d\n", events[i].data.fd);

            } else if (events[i].data.fd == sfd) {

                for (;;) {

                    connfd = accept(sfd, NULL, NULL);

                    if (connfd == -1) {
                        if ((errno != EAGAIN) &&
                                (errno != EWOULDBLOCK)) {
                            perror("accept");
                        }
                        break;
                    }

                    if (set_fl(connfd, O_NONBLOCK) < 0) {
                        perror("set_fl");
                        exit(EXIT_FAILURE);
                    }

                    if (fd_add(efd, connfd) < 0) {
                        perror("fd_add");
                        exit(EXIT_FAILURE);
                    }

                    http = http_new(connfd, list_dir, sock_read, writen_nonblock);
                    
                    fprintf(stderr, "put fd = %d:sfd = %d http = %p\n", connfd, sfd, http);
                    tor_array_put(cache_sock, connfd, &http);
                }

            } else {
                fprintf(stderr, "get fd = %d\n", events[i].data.fd);
                http = *(http_context **)tor_array_get(cache_sock, events[i].data.fd);
                fprintf(stderr, "fd = %d\n", http->fd);
                http_read_head(http);
                do_process(http);
                http_free(http);
            }

        }

        fprintf(stderr, "=============\n");
    }

    close(sfd);
    close(efd);
}
/* ----- the main ----- */
main(int argc, char *argv[])
{
    char    buf[BUF_SIZE];
    int     n;
    int     fVerbose;
    struct  sigaction    act;
    struct  sigaction    oldActInt; /* old handler for SIGINT  */ 
    struct  sigaction    oldActQuit; /* old handler for SIGQUIT */ 

    /* handle command line args, a very simple-minded approach */
    if (argc == 1) 
    {   /* no verbose flag ? */
        fVerbose = 0;
    }
    else if (argc == 2 && *argv[1] == '-' && *(argv[1]+1) == 'v')
    {   /* need verbose flag */
        fVerbose = 1;
    }
    else 
    {   /* wront command line */
        printf("Usage: %s [-v]", argv[0]);
        exit(0);
    }

    /* fill in the act */
    act.sa_handler = sigHandler;    /* point to the signal handler */
    sigemptyset(&act.sa_mask);      /* mask nothing */
    act.sa_flags = SA_RESTART;      /* restart interrupted system call */

    /* install SIGINT handler */
    if (sigaction(SIGINT, &act, &oldActInt) < 0)
    {
        perror("Failed to install handler for signal SIGINT");
        exit(-1);
    }

    /* install SIGQUIT handler */
    if (sigaction(SIGQUIT, &act, &oldActQuit) < 0)
    {
        perror("Failed to install handler for signal SIGQUIT");
        exit(-1);
    }

    /* make the stdin non-blocking */
    set_fl(STDIN_FILENO, O_NONBLOCK);

    write(STDOUT_FILENO, promptStr, sizeof(promptStr));

    /* loop forever */
    while (!fExit)
    {
        /* read from stdin, but can not be blocked */
        if ((n = read(STDIN_FILENO, buf, BUF_SIZE)) < 0)
        {
            /* just no data ? */
            if (errno == EAGAIN)
            {
                /* no input, sleep 1 to save the CPU cycle */
                sleep(1);

                /* for debug purpose */
                if (fVerbose)
                {
                    write(STDOUT_FILENO, ".", 1);
                }
            }
            else {
                perror("read failed");
                exit(-1);
            }
        }
        /* got something from the user */
        else
        {
            /* write to stdout whatever we read in */
            write(STDOUT_FILENO, buf, n);

            /* start with 'q' */
            if (buf[0] == 'q')
            {
                fExit = 1;
            }
            else
            {
                write(STDOUT_FILENO, promptStr, sizeof(promptStr));
            }
        }
    }

    /* restore signal handlers */
    sigaction(SIGINT, &oldActInt, NULL); 
    sigaction(SIGQUIT, &oldActQuit, NULL); 

    /* make the stdio blocking, again !!! */
    clr_fl(STDIN_FILENO, O_NONBLOCK);

    fflush(stdout);
}