Esempio n. 1
0
/**
 * @brief  Main function of whole server.
 *
 * @return	EXIT_SUCCESS - when forked properly
 * @return	EXIT_FAILURE - on error during server initialization
 * @return	0 - on application exit
 */
int main(void)
{
	pid_t pid, sid;
	int fd;
	int ret = 0;
	struct sigaction sa;
	char buff[16] = {0};

	sa.sa_handler = server_sig_handler;
	sigemptyset(&sa.sa_mask);
	sigaction(SIGTERM, &sa, NULL);

	openlog("ScopeServer", LOG_PID | LOG_LOCAL0,  LOG_LOCAL0);

	pid = fork();
	if(pid < 0) {
		syslog(LOG_ERR, "Fork failed, daemon couldn't start! (errno = %d)\n", -errno);
		return EXIT_FAILURE;
	} else if(pid > 0){
		return EXIT_SUCCESS;
	}

	openlog("ScopeServer", LOG_PID | LOG_LOCAL0,  LOG_LOCAL0);

	umask(0);

	syslog(LOG_INFO, "[ScopeServer]: Daemon started!\n");

	sid = setsid();
	if(sid < 0) {
		syslog(LOG_ERR, "Setsid failed, couldn't create new sid! (errno = %d)\n", -errno);
		return EXIT_FAILURE;
	}

	sprintf(buff, "%ld", (long)getpid());
	fd = open(SCOPE_FILE_PID, O_CREAT | O_WRONLY);
	if(fd <0) {
		syslog(LOG_ERR, "Couldn't create pid file! (errno = %d)\n", -errno);
		ret = EXIT_FAILURE;
		goto init_fail;
	}

	if(write(fd, buff, strlen(buff)+1) < 0) {
		syslog(LOG_ERR, "Couldn't save pid file for ScopeServer! (errno = %d)\n", -errno);
		close(fd);
		ret = EXIT_FAILURE;
		goto init_fail;
	}
	close(fd);

	if(mkfifo(SCOPE_FILE_FIFO, O_RDWR) < 0) {
		syslog(LOG_ERR, "Couldn't create fifo file: %s! (errno = %d)\n", SCOPE_FILE_FIFO, -errno);
		ret = EXIT_FAILURE;
		goto init_fail;
	}

	if(chdir("/") < 0) {
		syslog(LOG_ERR, "Chdir failed! (errno = %d)\n", -errno);
		ret = EXIT_FAILURE;
		goto init_fail;
	}

	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	if(server_init() < 0) {
		syslog(LOG_ERR, "Unable to initizalize the server! (errno = %d)\n", -errno);
		ret = EXIT_FAILURE;
		goto init_fail;
	}

	server_start();

init_fail:
	unlink(SCOPE_FILE_FIFO);
	unlink(SCOPE_FILE_PID);
	closelog();

	return ret;
}
Esempio n. 2
0
/*
	dbgconnect(cProgramNname|nPid) -> lResult
*/
int
clip_DBGCONNECT(ClipMachine * ClipMachineMemory)
{
#ifdef _WIN32
   return EG_ARG;
#else
   ClipVar *vp = _clip_par(ClipMachineMemory, 1);

   pid_t dpid = 0;

   if (!vp)
      return EG_ARG;

   if (vp->ClipType_t_of_ClipVar.ClipVartype_type_of_ClipType == NUMERIC_type_of_ClipVarType)
      dpid = _clip_double(vp);
   else if (vp->ClipType_t_of_ClipVar.ClipVartype_type_of_ClipType == CHARACTER_type_of_ClipVarType)
   {
      char path[256];

      FILE *file;

      char *s = _clip_parc(ClipMachineMemory, 1);

      if (!s || !*s)
	 return EG_ARG;

      snprintf(path, sizeof(path), "pidof -s %s", s);
      file = popen(path, "r");
      if (file)
      {
	 unsigned long ul;

	 if (fscanf(file, "%lu", &ul) == 1)
	    dpid = ul;
	 pclose(file);
      }
   }

   if (!dpid)
      return EG_ARG;

   pid = dpid;

   if (!cleanup_installed)
   {
      cleanup_installed = 1;
      signal(SIGPIPE, dbg_signal);
      atexit(cleanup);
   }

   snprintf(in_path, sizeof(in_path), "/tmp/clip_dbg.%lu.in", (unsigned long) pid);
   remove(in_path);
   if (mkfifo(in_path, 0600))
   {
      _clip_trap_printf(ClipMachineMemory, ClipMachineMemory->fp->filename_of_ClipFrame,
			ClipMachineMemory->fp->line_of_ClipFrame, "DBGCONNECT: cannot create FIFO '%s': %s\n", in_path, strerror(errno));
      cleanup();
      return -1;
   }

   _clip_logg(1, "fifo %s created successfully", in_path);

   snprintf(out_path, sizeof(out_path), "/tmp/clip_dbg.%lu.out", (unsigned long) pid);
   remove(out_path);
   if (mkfifo(out_path, 0600))
   {
      _clip_trap_printf(ClipMachineMemory, ClipMachineMemory->fp->filename_of_ClipFrame,
			ClipMachineMemory->fp->line_of_ClipFrame, "DBGCONNECT: cannot create FIFO '%s': %s\n", out_path, strerror(errno));
      cleanup();
      return -1;
   }
   _clip_logg(1, "fifo %s created successfully", out_path);

   if (kill(pid, SIGUSR1))
   {
      _clip_trap_printf(ClipMachineMemory, ClipMachineMemory->fp->filename_of_ClipFrame,
			ClipMachineMemory->fp->line_of_ClipFrame, "DBGCONNECT: cannot send signal SIGUSR1 to pid %lu: %s\n", (unsigned long) pid, strerror(errno));
      cleanup();
      return -1;
   }
   _clip_logg(1, "signal SIGUSR1 sent to pid %lu", (unsigned long) pid);

   fin = fopen(in_path, "wt");
   if (!fin)
   {
      _clip_trap_printf(ClipMachineMemory, ClipMachineMemory->fp->filename_of_ClipFrame, ClipMachineMemory->fp->line_of_ClipFrame, "DBGCONNECT: cannot open FIFO '%s': %s\n", in_path, strerror(errno));
      cleanup();
      return -1;
   }
   setvbuf(fin, 0, _IOLBF, 0);
   fwrite("\n", 1, 1, fin);
   _clip_logg(1, "fifo %s opened for writing", in_path);

   fout = fopen(out_path, "rt");
   if (!fout)
   {
      _clip_trap_printf(ClipMachineMemory, ClipMachineMemory->fp->filename_of_ClipFrame,
			ClipMachineMemory->fp->line_of_ClipFrame, "DBGCONNECT: cannot open FIFO '%s': %s\n", out_path, strerror(errno));
      cleanup();
      return -1;
   }
   /*setvbuf(fout, 0, _IOLBF, 0); */

   _clip_logg(1, "fifo %s opened for reading", out_path);
   _clip_retl(ClipMachineMemory, 1);

   for (;;)
   {
      char buf[4096];

      if (!fgets(buf, 4096, fout))
      {
	 _clip_trap_printf(ClipMachineMemory, ClipMachineMemory->fp->filename_of_ClipFrame, ClipMachineMemory->fp->line_of_ClipFrame, "DBGCOMMAND: cannot read data");
	 cleanup();
	 return -1;
      }
      if (!strcmp(buf, ".\n"))
	 break;
   }

   return 0;
#endif
}
Esempio n. 3
0
rtems_task Init(
  rtems_task_argument not_used
)
{
  int fd = -1;
  int status = -1;
  off_t offset = 4;
  int pipe_length = -1;
  int flag = 1;

  puts( "\n\n*** TEST PIPE/FIFO - 04 ***" );

  puts( "Init - Creating /fifo" );
  status = mkfifo( "/fifo", 0777 );
  rtems_test_assert( status == 0 );
  
  puts( "Init - Opening /fifo in readonly, non-blocking mode" );
  fd = open( "/fifo", O_RDONLY | O_NONBLOCK );
  rtems_test_assert( fd != -1 );
  
  puts( "Init - Attempt to lseek on fifo -- Expected ESPIPE" );
  offset = lseek( fd, offset, SEEK_CUR );
  rtems_test_assert( offset == -1 );
  rtems_test_assert( errno == ESPIPE );

  puts( "Init - ioctl: FIONBIO -- Expected EFAULT" );
  status = ioctl( fd, FIONBIO, NULL );
  rtems_test_assert( status == -1 );
  rtems_test_assert( errno == EFAULT );

  puts( "Init - ioctl: FIONBIO -- OK" );
  status = ioctl( fd, FIONBIO, &flag );
  rtems_test_assert( status == 0 );
 
  flag = 0;
  puts( "Init - ioctl: FIONBIO -- OK" );
  status = ioctl( fd, FIONBIO, &flag );
  rtems_test_assert( status == 0 );

  puts( "Init - ioctl: Dummy Command -- Expected EINVAL" );
  status = ioctl( fd, -1, NULL );
  rtems_test_assert( status == -1 );
  rtems_test_assert( errno == EINVAL );

  puts( "Init - ioctl: FIONREAD -- Expected EFAULT" );
  status = ioctl( fd, FIONREAD, NULL );
  rtems_test_assert( status == -1 );
  rtems_test_assert( errno == EFAULT );

  puts( "Init - ioctl: FIONREAD -- OK" );
  status = ioctl( fd, FIONREAD, &pipe_length );
  rtems_test_assert( status == 0 );
  rtems_test_assert( pipe_length == 0 );
  
  puts( "Init - closing /fifo" );
  status = close( fd );
  rtems_test_assert( status == 0 );
  
  puts( "Init - removing /fifo" );
  status = unlink( "/fifo" );
  rtems_test_assert( status == 0 );

  puts( "*** END OF TEST PIPE/FIFO - 04 ***" );
  rtems_test_exit(0);
}
Esempio n. 4
0
/*
 * Create the file, or the directory
 *
 * fname is the original filename
 * ofile is the output filename (may be in a different directory)
 *
 * Returns:  CF_SKIP     if file should be skipped
 *           CF_ERROR    on error
 *           CF_EXTRACT  file created and data to restore
 *           CF_CREATED  file created no data to restore
 *
 * Note, we create the file here, except for special files,
 * we do not set the attributes because we want to first
 * write the file, then when the writing is done, set the
 * attributes.
 *
 * So, we return with the file descriptor open for normal files.
 */
int create_file(JCR *jcr, ATTR *attr, BFILE *bfd, int replace)
{
   mode_t new_mode, parent_mode;
   int flags;
   uid_t uid;
   gid_t gid;
   int pnl;
   bool exists = false;
   struct stat mstatp;
#ifndef HAVE_WIN32
   bool isOnRoot;
#endif

   bfd->reparse_point = false;
   if (is_win32_stream(attr->data_stream)) {
      set_win32_backup(bfd);
   } else {
      set_portable_backup(bfd);
   }

   new_mode = attr->statp.st_mode;
   Dmsg3(200, "type=%d newmode=%x file=%s\n", attr->type, new_mode, attr->ofname);
   parent_mode = S_IWUSR | S_IXUSR | new_mode;
   gid = attr->statp.st_gid;
   uid = attr->statp.st_uid;

#ifdef HAVE_WIN32
   if (!bfd->use_backup_api) {
      /*
       * Eliminate invalid windows filename characters from foreign filenames
       */
      char *ch = (char *)attr->ofname;
      if (ch[0] != 0 && ch[1] != 0) {
         ch += 2;
         while (*ch) {
            switch (*ch) {
            case ':':
            case '<':
            case '>':
            case '*':
            case '?':
            case '|':
               *ch = '_';
                break;
            }
            ch++;
         }
      }
   }
#endif

   Dmsg2(400, "Replace=%c %d\n", (char)replace, replace);
   if (lstat(attr->ofname, &mstatp) == 0) {
      exists = true;
      switch (replace) {
      case REPLACE_IFNEWER:
         if (attr->statp.st_mtime <= mstatp.st_mtime) {
            Qmsg(jcr, M_INFO, 0, _("File skipped. Not newer: %s\n"), attr->ofname);
            return CF_SKIP;
         }
         break;
      case REPLACE_IFOLDER:
         if (attr->statp.st_mtime >= mstatp.st_mtime) {
            Qmsg(jcr, M_INFO, 0, _("File skipped. Not older: %s\n"), attr->ofname);
            return CF_SKIP;
         }
         break;
      case REPLACE_NEVER:
         /*
          * Set attributes if we created this directory
          */
         if (attr->type == FT_DIREND && path_list_lookup(jcr->path_list, attr->ofname)) {
            break;
         }
         Qmsg(jcr, M_INFO, 0, _("File skipped. Already exists: %s\n"), attr->ofname);
         return CF_SKIP;
      case REPLACE_ALWAYS:
         break;
      }
   }

   switch (attr->type) {
   case FT_RAW:                       /* Raw device to be written */
   case FT_FIFO:                      /* FIFO to be written to */
   case FT_LNKSAVED:                  /* Hard linked, file already saved */
   case FT_LNK:
   case FT_SPEC:                      /* Fifo, ... to be backed up */
   case FT_REGE:                      /* Empty file */
   case FT_REG:                       /* Regular file */
      /*
       * Note, we do not delete FT_RAW because these are device files
       * or FIFOs that should already exist. If we blow it away,
       * we may blow away a FIFO that is being used to read the
       * restore data, or we may blow away a partition definition.
       */
      if (exists && attr->type != FT_RAW && attr->type != FT_FIFO) {
         /* Get rid of old copy */
         Dmsg1(400, "unlink %s\n", attr->ofname);
         if (secure_erase(jcr, attr->ofname) == -1) {
            berrno be;

            Qmsg(jcr, M_ERROR, 0, _("File %s already exists and could not be replaced. ERR=%s.\n"),
                 attr->ofname, be.bstrerror());
            /* Continue despite error */
         }
      }

      /*
       * Here we do some preliminary work for all the above
       *   types to create the path to the file if it does
       *   not already exist.  Below, we will split to
       *   do the file type specific work
       */
      pnl = separate_path_and_file(jcr, attr->fname, attr->ofname);
      if (pnl < 0) {
         return CF_ERROR;
      }

      /*
       * If path length is <= 0 we are making a file in the root
       *  directory. Assume that the directory already exists.
       */
      if (pnl > 0) {
         char savechr;
         savechr = attr->ofname[pnl];
         attr->ofname[pnl] = 0;                 /* terminate path */

         if (!path_already_seen(jcr, attr->ofname, pnl)) {
            Dmsg1(400, "Make path %s\n", attr->ofname);
            /*
             * If we need to make the directory, ensure that it is with
             * execute bit set (i.e. parent_mode), and preserve what already
             * exists. Normally, this should do nothing.
             */
            if (!makepath(attr, attr->ofname, parent_mode, parent_mode, uid, gid, 1)) {
               Dmsg1(10, "Could not make path. %s\n", attr->ofname);
               attr->ofname[pnl] = savechr;     /* restore full name */
               return CF_ERROR;
            }
         }
         attr->ofname[pnl] = savechr;           /* restore full name */
      }

      /*
       * Now we do the specific work for each file type
       */
      switch(attr->type) {
      case FT_REGE:
      case FT_REG:
         Dmsg1(100, "Create=%s\n", attr->ofname);
         flags = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY; /*  O_NOFOLLOW; */
         if (IS_CTG(attr->statp.st_mode)) {
            flags |= O_CTG;              /* set contiguous bit if needed */
         }

         if (is_bopen(bfd)) {
            Qmsg1(jcr, M_ERROR, 0, _("bpkt already open fid=%d\n"), bfd->fid);
            bclose(bfd);
         }

         if (bopen(bfd, attr->ofname, flags, 0, attr->statp.st_rdev) < 0) {
            berrno be;

            be.set_errno(bfd->berrno);
            Qmsg2(jcr, M_ERROR, 0, _("Could not create %s: ERR=%s\n"), attr->ofname, be.bstrerror());
            Dmsg2(100,"Could not create %s: ERR=%s\n", attr->ofname, be.bstrerror());

            return CF_ERROR;
         }

         return CF_EXTRACT;

#ifndef HAVE_WIN32 /* None of these exist in MS Windows */
      case FT_RAW:                    /* Bareos raw device e.g. /dev/sda1 */
      case FT_FIFO:                   /* Bareos fifo to save data */
      case FT_SPEC:
         flags = O_WRONLY | O_BINARY;

         isOnRoot = bstrcmp(attr->fname, attr->ofname) ? 1 : 0;
         if (S_ISFIFO(attr->statp.st_mode)) {
            Dmsg1(400, "Restore fifo: %s\n", attr->ofname);
            if (mkfifo(attr->ofname, attr->statp.st_mode) != 0 && errno != EEXIST) {
               berrno be;
               Qmsg2(jcr, M_ERROR, 0, _("Cannot make fifo %s: ERR=%s\n"),
                     attr->ofname, be.bstrerror());
               return CF_ERROR;
            }
         } else if (S_ISSOCK(attr->statp.st_mode)) {
             Dmsg1(200, "Skipping restore of socket: %s\n", attr->ofname);
#ifdef S_IFDOOR /* Solaris high speed RPC mechanism */
         } else if (S_ISDOOR(attr->statp.st_mode)) {
             Dmsg1(200, "Skipping restore of door file: %s\n", attr->ofname);
#endif
#ifdef S_IFPORT /* Solaris event port for handling AIO */
         } else if (S_ISPORT(attr->statp.st_mode)) {
             Dmsg1(200, "Skipping restore of event port file: %s\n", attr->ofname);
#endif
         } else if ((S_ISBLK(attr->statp.st_mode) || S_ISCHR(attr->statp.st_mode)) && !exists && isOnRoot) {
             /*
              * Fatal: Restoring a device on root-file system, but device node does not exist.
              * Should not create a dump file.
              */
             Qmsg1(jcr, M_ERROR, 0, _("Device restore on root failed, device %s missing.\n"), attr->fname);
             return CF_ERROR;
         } else if (S_ISBLK(attr->statp.st_mode) || S_ISCHR(attr->statp.st_mode)) {
             Dmsg1(400, "Restoring a device as a file: %s\n", attr->ofname);
             flags = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY;
         } else {
            Dmsg1(400, "Restore node: %s\n", attr->ofname);
            if (mknod(attr->ofname, attr->statp.st_mode, attr->statp.st_rdev) != 0 && errno != EEXIST) {
               berrno be;
               Qmsg2(jcr, M_ERROR, 0, _("Cannot make node %s: ERR=%s\n"),
                     attr->ofname, be.bstrerror());
               return CF_ERROR;
            }
         }

         /*
          * Here we are going to attempt to restore to a FIFO, which
          * means that the FIFO must already exist, AND there must
          * be some process already attempting to read from the
          * FIFO, so we open it write-only.
          */
         if (attr->type == FT_RAW || attr->type == FT_FIFO) {
            btimer_t *tid;
            Dmsg1(400, "FT_RAW|FT_FIFO %s\n", attr->ofname);
            /*
             * Timeout open() in 60 seconds
             */
            if (attr->type == FT_FIFO) {
               Dmsg0(400, "Set FIFO timer\n");
               tid = start_thread_timer(jcr, pthread_self(), 60);
            } else {
               tid = NULL;
            }
            if (is_bopen(bfd)) {
               Qmsg1(jcr, M_ERROR, 0, _("bpkt already open fid=%d\n"), bfd->fid);
            }
            Dmsg2(400, "open %s flags=0x%x\n", attr->ofname, flags);
            if ((bopen(bfd, attr->ofname, flags, 0, 0)) < 0) {
               berrno be;
               be.set_errno(bfd->berrno);
               Qmsg2(jcr, M_ERROR, 0, _("Could not open %s: ERR=%s\n"),
                     attr->ofname, be.bstrerror());
               Dmsg2(400, "Could not open %s: ERR=%s\n", attr->ofname, be.bstrerror());
               stop_thread_timer(tid);
               return CF_ERROR;
            }
            stop_thread_timer(tid);
            return CF_EXTRACT;
         }
         Dmsg1(400, "FT_SPEC %s\n", attr->ofname);
         return CF_CREATED;

      case FT_LNKSAVED:                  /* Hard linked, file already saved */
         Dmsg2(130, "Hard link %s => %s\n", attr->ofname, attr->olname);
         if (link(attr->olname, attr->ofname) != 0) {
            berrno be;
#ifdef HAVE_CHFLAGS
            struct stat s;

            /*
             * If using BSD user flags, maybe has a file flag preventing this.
             * So attempt to disable, retry link, and reset flags.
             * Note that BSD securelevel may prevent disabling flag.
             */
            if (stat(attr->olname, &s) == 0 && s.st_flags != 0) {
               if (chflags(attr->olname, 0) == 0) {
                  if (link(attr->olname, attr->ofname) != 0) {
                     /*
                      * Restore original file flags even when linking failed
                      */
                     if (chflags(attr->olname, s.st_flags) < 0) {
                        Qmsg2(jcr, M_ERROR, 0, _("Could not restore file flags for file %s: ERR=%s\n"),
                              attr->olname, be.bstrerror());
                     }
#endif /* HAVE_CHFLAGS */
            Qmsg3(jcr, M_ERROR, 0, _("Could not hard link %s -> %s: ERR=%s\n"),
                  attr->ofname, attr->olname, be.bstrerror());
            Dmsg3(200, "Could not hard link %s -> %s: ERR=%s\n",
                  attr->ofname, attr->olname, be.bstrerror());
            return CF_ERROR;
#ifdef HAVE_CHFLAGS
                  }
                  /*
                   * Finally restore original file flags
                   */
                  if (chflags(attr->olname, s.st_flags) < 0) {
                     Qmsg2(jcr, M_ERROR, 0, _("Could not restore file flags for file %s: ERR=%s\n"),
                            attr->olname, be.bstrerror());
                  }
               } else {
                 Qmsg2(jcr, M_ERROR, 0, _("Could not reset file flags for file %s: ERR=%s\n"),
                       attr->olname, be.bstrerror());
               }
            } else {
              Qmsg3(jcr, M_ERROR, 0, _("Could not hard link %s -> %s: ERR=%s\n"),
                    attr->ofname, attr->olname, be.bstrerror());
              return CF_ERROR;
            }
#endif /* HAVE_CHFLAGS */

         }
         return CF_CREATED;

#endif /* HAVE_WIN32 */
#ifdef HAVE_WIN32
      case FT_LNK:
         /*
          * Handle Windows Symlink-Like Reparse Points
          * - Directory Symlinks
          * - File Symlinks
          * - Volume Mount Points
          * - Junctions
          */
         Dmsg2(130, "FT_LNK should restore: %s -> %s\n", attr->ofname, attr->olname);
         if (attr->statp.st_rdev & FILE_ATTRIBUTE_VOLUME_MOUNT_POINT) {
            /*
             * We do not restore volume mount points
             */
            Dmsg0(130, "Skipping Volume Mount Point\n");
            return CF_SKIP;
         }
         if (win32_symlink(attr->olname, attr->ofname, attr->statp.st_rdev) != 0 && errno != EEXIST) {
            berrno be;
            Qmsg3(jcr, M_ERROR, 0, _("Could not symlink %s -> %s: ERR=%s\n"),
                  attr->ofname, attr->olname, be.bstrerror());
            return CF_ERROR;
         }
         return CF_CREATED;
#else
      case FT_LNK:
         /*
          * Unix/Linux symlink handling
          */
         Dmsg2(130, "FT_LNK should restore: %s -> %s\n", attr->ofname, attr->olname);
         if (symlink(attr->olname, attr->ofname) != 0 && errno != EEXIST) {
            berrno be;
            Qmsg3(jcr, M_ERROR, 0, _("Could not symlink %s -> %s: ERR=%s\n"),
                  attr->ofname, attr->olname, be.bstrerror());
            return CF_ERROR;
         }
         return CF_CREATED;
#endif
      } /* End inner switch */

   case FT_REPARSE:
   case FT_JUNCTION:
      bfd->reparse_point = true;
      /*
       * Fall through wanted
       */
   case FT_DIRBEGIN:
   case FT_DIREND:
      Dmsg2(200, "Make dir mode=%o dir=%s\n", new_mode, attr->ofname);
      if (!makepath(attr, attr->ofname, new_mode, parent_mode, uid, gid, 0)) {
         return CF_ERROR;
      }
      /*
       * If we are using the Win32 Backup API, we open the directory so
       * that the security info will be read and saved.
       */
      if (!is_portable_backup(bfd)) {
         if (is_bopen(bfd)) {
            Qmsg1(jcr, M_ERROR, 0, _("bpkt already open fid=%d\n"), bfd->fid);
         }
         if (bopen(bfd, attr->ofname, O_WRONLY | O_BINARY, 0, attr->statp.st_rdev) < 0) {
            berrno be;
            be.set_errno(bfd->berrno);
#ifdef HAVE_WIN32
            /*
             * Check for trying to create a drive, if so, skip
             */
            if (attr->ofname[1] == ':' &&
                IsPathSeparator(attr->ofname[2]) &&
                attr->ofname[3] == '\0') {
               return CF_SKIP;
            }
#endif
            Qmsg2(jcr, M_ERROR, 0, _("Could not open %s: ERR=%s\n"),
                  attr->ofname, be.bstrerror());
            return CF_ERROR;
         }
         return CF_EXTRACT;
      } else {
         return CF_CREATED;
      }

   case FT_DELETED:
      Qmsg2(jcr, M_INFO, 0, _("Original file %s have been deleted: type=%d\n"), attr->fname, attr->type);
      break;
   /*
    * The following should not occur
    */
   case FT_NOACCESS:
   case FT_NOFOLLOW:
   case FT_NOSTAT:
   case FT_DIRNOCHG:
   case FT_NOCHG:
   case FT_ISARCH:
   case FT_NORECURSE:
   case FT_NOFSCHG:
   case FT_NOOPEN:
      Qmsg2(jcr, M_ERROR, 0, _("Original file %s not saved: type=%d\n"), attr->fname, attr->type);
      break;
   default:
      Qmsg2(jcr, M_ERROR, 0, _("Unknown file type %d; not restored: %s\n"), attr->type, attr->fname);
      break;
   }
   return CF_ERROR;
}
Esempio n. 5
0
int main(void) {

    int fdsrv, bread;
    struct bunch msg;
    int i=0;
    int j=0;
    int ret;
    int wynik;
    int sem[4];
    int def_val[] = {X1,X2,X3,X4};

    if(mkfifo("fifo_server", S_IFIFO|0755) == -1) {
        perror("Tworzenie fifo_server");
        exit(EXIT_FAILURE);
    }


    for(i=0; i<4; i++)
        if((sem[i] = semget(1111*(i+1), def_val[i], IPC_CREAT|0755)) == -1 ) {
            perror("Semafor create");
            exit(EXIT_FAILURE);
        }

    for(i=0; i<4; i++)
        for(j=0; j<def_val[i]; j++)
            if(semctl(sem[i], j, SETVAL, i+1) == -1) {
                perror("Nadawanie wartosci sem");
                exit(EXIT_FAILURE);
            }

    if((fdsrv = open("fifo_server", O_RDONLY)) == -1) {
        perror("Otwieranie kolejki fifo_server");
        exit(EXIT_FAILURE);
    }

    while(1) {

        bread = read(fdsrv, &msg, sizeof(msg));
        if(bread < 0) {
            perror("blad read in while(1)");
            exit(EXIT_FAILURE);
        }
        if(bread > 0) {
            printf("Bunch %d\n",i++);
            printf("Message received from client %d\n", msg.id);
            printf("There is %d people who wants to eat\n", msg.size);
            sendResponse(msg, sem);
            for(i=1; i<4; i++) {
                for(j=0; j<def_val[i]; j++) {
                    if( (ret = semctl(sem[i], j, GETVAL,0)) == -1) {
                        perror("semctl\n");
                        exit(EXIT_FAILURE);
                    }
                    wynik = def_val[i] - ret;
                    wynik = (wynik <0) ? 0 : wynik;
                    printf("Stolik dla %d, zajete %d\n", i+1, wynik);
                }

            }
        }


    }


    return 0;
}
Esempio n. 6
0
int ConvertToMp3_o( CONVDATA *cn) {
  int pid,status;
  CONVDATA Cn;
  Cn= *cn;
  Ssec= cn->StartSec;
  Esec= cn->EndSec;
  if(!CheckMedia(cn->infile)){
       return 0;
  }
  if(Esec < 0) {
    cn->EndSec = Minfo.TotSec +Esec;
    Esec= cn->EndSec;
  }
  if(Esec > Minfo.TotSec) {
    cn->EndSec = Minfo.TotSec ;
    Esec= cn->EndSec;
  }
  
  strcpy(GrabFileName,cn->outfile);
  if ((pid=fork())==0) {
    char command[500],Fifo[100],options[100];
    sprintf(Fifo,"/tmp/Fifo%-d",getpid());
    mkfifo(Fifo,0600);
    if ((pid=fork())==0) {
     options[0] ='\0';
     if(fabs(cn->Enhfac-1.0)> 0.1) {
       switch(cn->VolEnh) {
         case 1:
          sprintf(options," --scale-l %lf ",cn->Enhfac);
          break;
         case 2:
          sprintf(options," --scale-r %lf ",cn->Enhfac);
          break;
         case 3:
          sprintf(options," --scale %lf ",cn->Enhfac);
          break;
       }
     }
     switch(cn->Quality) {
       case 1:
          strcat(options," -V0 -q 0 ");
          break;
       case 2:
          strcat(options," -V2 -q 2 ");
          break;
       case 3:
          strcat(options," -V4 -q 4 ");
          break;
     }
     sprintf(command,"kglame --quiet %-s  %-s \"%-s\"",options,Fifo,Cn.outfile); 
//     printf("%s\n",command);
     runfunction(command,NULL,kgLame);
//     fprintf(stderr,"Lame over\n");
     exit(0);
    }
    else {
      options[0] ='\0';
      if(cn->FullRange != 1) {
        int sh,sm,ss,smil,secs,eh,em,es,emil;
        float frac;
        secs = cn->StartSec;
        smil = (cn->StartSec - secs)*1000;
        ss = secs%60;
        secs = secs/60;
        sm = secs%60;
        sh = secs/60;
        if(cn->EndSec <=cn->StartSec ) cn->EndSec=0;
        secs = cn->EndSec-cn->StartSec;
        emil = (cn->EndSec-cn->StartSec -secs)*1000;
        es = secs%60;
        secs = secs/60;
        em = secs%60;
        eh = secs/60;
        if(cn->EndSec > 0) {
          sprintf(options," -ss %-d:%-d:%-d.%-d -endpos %-d:%-d:%-d.%-d",
              sh,sm,ss,smil,eh,em,es,emil);
        }
        else {
          sprintf(options," -ss %-d:%-d:%-d.%-d ",
              sh,sm,ss,smil);
        }
      }
      sprintf(command,"Mplayer -vo null -ao pcm:file=%-s %s \"%-s\"",
             Fifo,options,Cn.infile);
//      printf("%s\n",command);
      runfunction(command,ProcessMp3Conversion,Mplayer);
//      close(open(Fifo,O_RDONLY));
//      fprintf(stderr,"Removing Fifo\n");
      remove(Fifo);
      waitpid(pid,&status,0);
    }
    exit(0);
  }
  else {
     waitpid(pid,&status,0);
  }
}
Esempio n. 7
0
void init (int argc,char *argv[])
{
    struct lac *lac;
    struct in_addr listenaddr;
    struct utsname uts;

    init_args (argc,argv);
    srand( time(NULL) );
    rand_source = 0;
    init_addr ();
    if (init_config ())
    {
        l2tp_log (LOG_CRIT, "%s: Unable to load config file\n", __FUNCTION__);
        exit (1);
    }
    if (uname (&uts)<0)
    {
        l2tp_log (LOG_CRIT, "%s : Unable to determine host system\n",
             __FUNCTION__);
        exit (1);
    }
    init_tunnel_list (&tunnels);
    if (init_network ())
        exit (1);

    if (gconfig.daemon)
        daemonize ();

    consider_pidfile();

    signal (SIGTERM, &sigterm_handler);
    signal (SIGINT, &sigint_handler);
    signal (SIGCHLD, &sigchld_handler);
    signal (SIGUSR1, &sigusr1_handler);
    signal (SIGHUP, &sighup_handler);
    init_scheduler ();

    unlink(gconfig.controlfile);
    mkfifo (gconfig.controlfile, 0600);

    open_controlfd();

    l2tp_log (LOG_INFO, "xl2tpd version " SERVER_VERSION " started on %s PID:%d\n",
         hostname, getpid ());
    l2tp_log (LOG_INFO,
         "Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.\n");
    l2tp_log (LOG_INFO, "Forked by Scott Balmos and David Stipp, (C) 2001\n");
    l2tp_log (LOG_INFO, "Inherited by Jeff McAdams, (C) 2002\n");
    l2tp_log (LOG_INFO, "Forked again by Xelerance (www.xelerance.com) (C) 2006\n");
    listenaddr.s_addr = gconfig.listenaddr;
    l2tp_log (LOG_INFO, "Listening on IP address %s, port %d\n",
              inet_ntoa(listenaddr), gconfig.port);
    lac = laclist;
    while (lac)
    {
        if (lac->autodial)
        {
#ifdef DEBUG_MAGIC
            l2tp_log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
                 lac->entname[0] ? lac->entname : "(unnamed)");
#endif
            lac->active = -1;
            switch_io = 1;      /* If we're a LAC, autodials will be ICRQ's */
            magic_lac_dial (lac);
        }
        lac = lac->next;
    }
}
Esempio n. 8
0
File: eet.c Progetto: mgeorg/eet
int main(int argc, char **argv) {
  int fd;
  int pty;
  int ret;
  char ptyName[80];

  const char* ifnames[MAXFIFO];
  const char* cfname = NULL;
  const char* ofname = NULL;
  const char* dfname = NULL;
  const char* debugfname = NULL;
  int numPrompts = 0;
  char *prompts[MAXPROMPTS];
  int normalPrompt[MAXPROMPTS];
  int fifos[MAXFIFO];
  int numFifo=0;
  int dumpFd=-1;
  int outFd=-1;
  int controlFd=-1;
  int laxWaitForReadline=0;

  pamperReadline = 0;
  clearPendingOnInterrupt = 0;
  clearPending = 0;
  doStatusReport = 0;
  int doEcho = 1;

  int c;
  while ((c = getopt(argc, argv, "+i:o:c:d:D:r:R:e::l::z::")) != -1) {
    switch(c) {
    case 'i':
      if(numFifo >= MAXFIFO) {
        fprintf(stderr,"too many fifo\n");
        exit(1);
      }
      ifnames[numFifo] = optarg;
      numFifo++;
      break;
    case 'o':
      ofname = optarg;
      break;
    case 'c':
      cfname = optarg;
      break;
    case 'd':
      dfname = optarg;
      break;
    case 'D':
      debugfname = optarg;
      break;
    case 'R':
    case 'r':
      if(numPrompts >= MAXPROMPTS) {
        fprintf(stderr,"too many prompts\n");
        exit(1);
      }
      pamperReadline = 1;
      prompts[numPrompts] = optarg;
      if(c=='R') {
        normalPrompt[numPrompts] = 0;
        if(*prompts[numPrompts] == '\0') {
          write(2,"can't have empty string be non-normal prompt\n",45);
          normalPrompt[numPrompts] = 1;
        }
      } else {
        normalPrompt[numPrompts] = 1;
      }
      numPrompts++;
      break;
    case 'e':
      doEcho = 0;
      if(optarg) {
        doEcho = strtol(optarg,NULL,10);
      }
      break;
    case 'l':
      laxWaitForReadline = 0;
      if(optarg) {
        laxWaitForReadline = strtol(optarg,NULL,10);
      }
      break;
    case 'z':
      clearPendingOnInterrupt = 1;
      clearPending = 1; // to show that 
      if(optarg) {
        clearPendingOnInterrupt = strtol(optarg,NULL,10);
      }
      break;
    }
  }
  if(pamperReadline && !clearPending) {
    clearPendingOnInterrupt = 1; // default with readline if not set explicitly
    clearPending = 0;
  }

  quit = 0;
  struct termios origTermData;
  tcgetattr(0,&origTermData);

//  openpty(&fd,&slave,NULL,&tt,&win);
//  fd = getpt();
  // perhaps O_ASYNC is interesting
  fd = open("/dev/ptmx", O_RDWR|O_NOCTTY);
  if(fd == -1) {
    printf("error with getpt\n");
    exit(1);
  }
  ret = grantpt(fd);
  if(ret != 0) {
    printf("error with grantpt\n");
    exit(1);
  }
  ret = unlockpt(fd);
  if(ret != 0) {
    printf("error with unlockpt\n");
    exit(1);
  }

  switch(childpid = fork()) {
  case -1:
    printf("ERROR!!!!\n");
    exit(1);
  case 0:
//    printf("child\n");
    ret = ptsname_r(fd,ptyName,80);
    if(ret != 0) {
      printf("ERROR: ptsname\n");
      exit(1);
    }
    pty = open(ptyName,O_RDWR);
    if(pty == -1) {
      printf("ERROR: could not open '%s'\n",ptyName);
      exit(1);
    }
    if(doEcho) {
      tcsetattr(pty,TCSANOW,&origTermData);
    } else {
      struct termios termData;
      int setTerm=0;
      setTerm = 1;
      termData = origTermData;
      termData.c_lflag &= ~ECHO;
      tcsetattr(pty,TCSANOW,&termData);
    }
    if(pty == 0) {
      printf("ERROR: tcsetattr (in child)\n");
      exit(1);
    }
    close(0);
    close(1);
    close(2);
    dup2(pty,0);
    dup2(pty,1);
    dup2(pty,2);
    setsid(); // connect the new process to the tty

    ret = ioctl(0, TIOCSCTTY, 0);
    if(ret == -1) {
      printf("error with ioctl\n");
      fflush(stdout);
      exit(1);
    }
    close(fd);
    close(pty);
//    char program[80] = "echoAsterix";
//    char arg1[80] = "--raw";
    char program[80] = "R";
    char arg1[80] = "--no-save";
//    char program[80] = "bash";
//    char arg1[80] = "";
    char *execArgs[3];
    execArgs[0] = program;
    execArgs[1] = arg1;
    execArgs[2] = (char*)NULL;
//    execArgs[1] = (char*)NULL;
    if(argc > optind) {
      execvp(argv[optind],&argv[optind]);
    } else {
      execvp(execArgs[0],execArgs);
    }
//    execlp("R", "--no-save", (char*)0);
//    execlp("matlab", "-nojvm", "-nosplash", "-nodesktop", (char*)0);
    printf("CHILD HAS AN ERROR...DIDN'T execlp");
    exit(1);
  }
//  printf("parent\n");
//  signal(SIGINT,SIG_IGN);
  signal(SIGCHLD,childDead);
//  signal(SIGUSR1,clearPamperReadline);
//  signal(SIGUSR2,setPamperReadline);
  signal(SIGINT,interruptHandler);
  signal(SIGUSR1,statusReportHandler);
  int i;

  struct stat statOfFile;

  int curFifo;
  for(curFifo=0;curFifo<numFifo;curFifo++) {
    ret = stat(ifnames[curFifo],&statOfFile);
    if(ret != 0) {
      if(errno == ENOENT) { // file does not exist, create it
        ret = mkfifo(ifnames[curFifo],S_IRWXU | S_IRWXG | S_IRWXO );
        if(ret != 0) {
          perror(argv[0]);
          exit(1);
        }
      } else {
        perror(argv[0]);
        exit(1);
      }
    } else {
      if(!S_ISFIFO(statOfFile.st_mode)) {
        printf("'%s' is not a FIFO\n",ifnames[curFifo]);
        exit(1);
      }
    }

    fifos[curFifo] = open(ifnames[curFifo],O_RDWR);
    if(fifos[curFifo] == -1) {
      printf("error opening FIFO '%s'\n",ifnames[curFifo]);
      exit(1);
    }
    struct flock fl;
    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;
    fl.l_pid = 0;
    if(fcntl(fifos[curFifo],F_SETLK,&fl) == -1) {
      fcntl(fifos[curFifo],F_GETLK,&fl);
      printf("fifo '%s' is locked by %d\n",ifnames[curFifo],fl.l_pid);
      close(fifos[curFifo]);
      exit(1);
    }
  }
  if(ofname) {
    outFd = open(ofname,O_WRONLY | O_CREAT | O_TRUNC,0644);
    if(outFd == -1) {
      printf("error opening file '%s'\n",ofname);
      exit(1);
    }
  }
  if(cfname) {
    // TODO make this a subroutine
    ret = stat(cfname,&statOfFile);
    if(ret != 0) {
      if(errno == ENOENT) { // file does not exist, create it
        ret = mkfifo(cfname,S_IRWXU | S_IRWXG | S_IRWXO );
        if(ret != 0) {
          perror(argv[0]);
          exit(1);
        }
      } else {
        perror(argv[0]);
        exit(1);
      }
    } else {
      if(!S_ISFIFO(statOfFile.st_mode)) {
        printf("'%s' is not a FIFO\n",cfname);
        exit(1);
      }
    }
    controlFd = open(cfname,O_RDWR);
    if(controlFd == -1) {
      printf("error opening control file '%s'\n",cfname);
      exit(1);
    }
    struct flock fl;
    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;
    fl.l_pid = 0;
    if(fcntl(controlFd,F_SETLK,&fl) == -1) {
      fcntl(controlFd,F_GETLK,&fl);
      printf("fifo '%s' is locked by %d\n",cfname,fl.l_pid);
      close(controlFd);
      exit(1);
    }
  }
  if(dfname) {
    dumpFd = open(dfname,O_WRONLY | O_CREAT | O_TRUNC,0644);
    if(dumpFd == -1) {
      printf("error opening file '%s'\n",dfname);
      exit(1);
    }
  }
  
  struct termios termData;
  int setTerm=0;
  setTerm = 1;
  termData = origTermData;
//  tcgetattr(0,&termData);
  cfmakeraw(&termData);
//  termData.c_iflag &= ~IGNBRK;
  if(clearPendingOnInterrupt) {
    // catch interrupts instead of passing them through the data stream.
    // We will interrupt child instead of letting the terminal do it.
    // This is usually undesirable since they can no longer control
    // interrupt behavior through their terminal.
    termData.c_lflag |= ISIG;
  }
//  termData.c_lflag &= ~ICANON;
//  termData.c_lflag &= ~ECHO;
//  termData.c_lflag |= ECHO; // local echo
//  termData.c_cc[VMIN] = 1;
//  termData.c_cc[VTIME] = 0;
  tcsetattr(0,TCSANOW,&termData);
//  if(argc>1 && strcmp(ifname,"--raw")==0) {
//  }

//  fcntl(fd,F_SETFL,O_NONBLOCK);

  fd_set readSet;
  fd_set writeSet;
  fd_set errorSet;
  int numBytes;
  int max;

  char toFdBuf[BUFSIZE];
  char *toFdPos = toFdBuf;
  int toFdSize = 0;
  char toOutBuf[BUFSIZE];
  char *toOutPos = toOutBuf;
  int toOutSize = 0;
  waitForReadline=0;
  char *posInPrompts[MAXPROMPTS];
  int curPrompt;
  for(curPrompt=0;curPrompt<numPrompts;curPrompt++) {
    posInPrompts[curPrompt] = prompts[curPrompt];
  }
  onNormalPrompt = 1;

  int debugfd=-1;
  if(debugfname) {
    debugfd = open(debugfname,O_WRONLY | O_CREAT | O_TRUNC,0644);
    if(debugfd == -1) {
      printf("error opening debug file '%s'",debugfname);
      exit(1);
    }
  }

  while(!quit) {
    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);
    FD_ZERO(&errorSet);

    max = -1;
    FD_SET(0,&errorSet);
    max = (max>0)?max:0;
    FD_SET(1,&errorSet);
    max = (max>1)?max:1;
    for(curFifo=0;curFifo<numFifo;curFifo++) {
      FD_SET(fifos[curFifo],&errorSet);
      max = (max>fifos[curFifo])?max:fifos[curFifo];
    }
    if(controlFd != -1) {
      FD_SET(controlFd,&errorSet);
      max = (max>controlFd)?max:controlFd;
    }
    FD_SET(fd,&errorSet);
    max = (max>fd)?max:fd;

    if(toFdSize < BUFSIZE) {
      FD_SET(0,&readSet);
      max = (max>0)?max:0;
      if(onNormalPrompt) {
        for(curFifo=0;curFifo<numFifo;curFifo++) {
          FD_SET(fifos[curFifo],&readSet);
          max = (max>fifos[curFifo])?max:fifos[curFifo];
        }
      }
    }
    if(toOutSize < BUFSIZE) {
      FD_SET(fd,&readSet);
      max = (max>fd)?max:fd;
    }
    if(controlFd != -1) {
      FD_SET(controlFd,&readSet);
      max = (max>controlFd)?max:controlFd;
    }

    if(!waitForReadline && toFdSize > 0) {
      FD_SET(fd,&writeSet);
      max = (max>fd)?max:fd;
    }
    if(toOutSize > 0) {
      FD_SET(1,&writeSet);
      max = (max>1)?max:1;
    }
//    ret = select(max+1,&readSet,&writeSet,&errorSet,NULL);
    struct timeval tv;
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    if(debugfd != -1) {
      char buf[1024];
      int size;
      size = snprintf(buf,1024,"%d%d%d%d %d%d%d%d %d%d%d%d - ",
                      FD_ISSET(0,&readSet),FD_ISSET(1,&readSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&readSet),
                      FD_ISSET(fd,&readSet),
                      FD_ISSET(0,&writeSet),FD_ISSET(1,&writeSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&writeSet),
                      FD_ISSET(fd,&writeSet),
                      FD_ISSET(0,&errorSet),FD_ISSET(1,&errorSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&errorSet),
                      FD_ISSET(fd,&errorSet));
      write(debugfd,buf,size);
    }
    errno = 0;
    if(doStatusReport) {
      char buf[1024];
      int size;
      size = snprintf(buf,1024,"before %d%d%d%d %d%d%d%d %d%d%d%d\r\n",
                      FD_ISSET(0,&readSet),FD_ISSET(1,&readSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&readSet),
                      FD_ISSET(fd,&readSet),
                      FD_ISSET(0,&writeSet),FD_ISSET(1,&writeSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&writeSet),
                      FD_ISSET(fd,&writeSet),
                      FD_ISSET(0,&errorSet),FD_ISSET(1,&errorSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&errorSet),
                      FD_ISSET(fd,&errorSet));
      write(1,buf,size);
      doStatusReport--;
    }
    ret = select(max+1,&readSet,&writeSet,&errorSet,&tv);
    if(doStatusReport) {
      char buf[1024];
      int size;
      size = snprintf(buf,1024,"after  %d%d%d%d %d%d%d%d %d%d%d%d\r\n",
                      FD_ISSET(0,&readSet),FD_ISSET(1,&readSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&readSet),
                      FD_ISSET(fd,&readSet),
                      FD_ISSET(0,&writeSet),FD_ISSET(1,&writeSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&writeSet),
                      FD_ISSET(fd,&writeSet),
                      FD_ISSET(0,&errorSet),FD_ISSET(1,&errorSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&errorSet),
                      FD_ISSET(fd,&errorSet));
      write(1,buf,size);
    }
    if(debugfd != -1) {
      char buf[1024];
      int size;
      size = snprintf(buf,1024,"%d%d%d%d %d%d%d%d %d%d%d%d ",
                      FD_ISSET(0,&readSet),FD_ISSET(1,&readSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&readSet),
                      FD_ISSET(fd,&readSet),
                      FD_ISSET(0,&writeSet),FD_ISSET(1,&writeSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&writeSet),
                      FD_ISSET(fd,&writeSet),
                      FD_ISSET(0,&errorSet),FD_ISSET(1,&errorSet),
                      FD_ISSET(numFifo>0?fifos[0]:0,&errorSet),
                      FD_ISSET(fd,&errorSet));
      write(debugfd,buf,size);
    }
    if(ret == -1) {
      if(errno == EINTR) {
        if(doStatusReport) {
          write(1,"caught a signal\r\n",strlen("caught a signal\r\n"));
        }
        if(debugfd != -1) {
          char buf = '\n';
          write(debugfd,&buf,1);
        }
        continue;
      } else {
        printf("select had an error\n");
        break;
      }
    }
    if(clearPending) {
      toFdSize = 0;
      clearPending = 0;
      if(debugfd != -1) {
        char buf = '\n';
        write(debugfd,&buf,1);
      }
      continue;
    }
    if(errno == EINTR) {
      write(1,"caught a signal with good return value\r\n",
            strlen("caught a signal with good return value\r\n"));
      if(debugfd != -1) {
        char buf = '\n';
        write(debugfd,&buf,1);
      }
      continue;
    }
    if(ret == 0) {
      if(debugfd != -1) {
        char buf = '\n';
        write(debugfd,&buf,1);
      }
      if(laxWaitForReadline) {
        waitForReadline = 0;
      }
      continue;
    }

    // check for errors
    if(FD_ISSET(0,&errorSet)) {
      error_at_line(0,errno,__FILE__,__LINE__,"0 is set in errorSet");
      break;
    }
    if(FD_ISSET(1,&errorSet)) {
      error_at_line(0,errno,__FILE__,__LINE__,"1 is set in errorSet");
      break;
    }
    for(curFifo=0;curFifo<numFifo;curFifo++) {
      if(FD_ISSET(fifos[curFifo],&errorSet)) {
        error_at_line(0,errno,__FILE__,__LINE__,
                      "fifos[%d] is set in errorSet",curFifo);
        break;
      }
    }
    if(FD_ISSET(fd,&errorSet)) {
      error_at_line(0,errno,__FILE__,__LINE__,"fd is set in errorSet");
      break;
    }
    if(controlFd != -1 && FD_ISSET(controlFd,&errorSet)) {
      error_at_line(0,errno,__FILE__,__LINE__,"controlFd is set in errorSet");
      break;
    }

    if(controlFd != -1 && FD_ISSET(controlFd,&readSet)) {
      // TODO not interrupt safe
      int k;
      char command;
      write(2,"eet command ",12);
      numBytes = read(controlFd,&command,1);
      if(numBytes != 1) continue;
      write(2,&command,1);
      write(2," '",2);
      char *buf = malloc(CONTROL_MSG_SIZE);
      buf[CONTROL_MSG_SIZE] = '\0';
      for(k=0;k<CONTROL_MSG_SIZE-1;k++) {
        numBytes = read(controlFd,&buf[k],1);
        if(numBytes != 1) {
          buf[k] = '\0';
          break;
        }
        if(buf[k] == '\0') {
          break;
        }
      }
      write(2,buf,strlen(buf));
      write(2,"'",1);
      if(numBytes != 1 || k >= CONTROL_MSG_SIZE-1) {
        write(2,"improperly terminated",21);
      }
      write(2,"\r\n",2);
      switch(command) {
      case 'R':
      case 'r':
        if(numPrompts >= MAXPROMPTS) {
          fprintf(stderr,"too many prompts\n");
          exit(1);
        }
        pamperReadline = 1;
        prompts[numPrompts] = buf;
        if(command=='R') {
          normalPrompt[numPrompts] = 0;
          if(*prompts[numPrompts] == '\0') {
            write(2,"can't have empty string be non-normal prompt\n",45);
            normalPrompt[numPrompts] = 1;
          }
        } else {
          normalPrompt[numPrompts] = 1;
        }
        posInPrompts[numPrompts] = prompts[numPrompts];
        numPrompts++;
        waitForReadline = 0;
        break;
      case '*':
        waitForReadline = 0;
        break;
      case 'p':
        waitForReadline = 0;
        pamperReadline = 0;
        if(buf && buf[0] != '\0') {
          pamperReadline = strtol(buf,NULL,10);
        }
        onNormalPrompt = 1;
        break;
      case 'l':
        laxWaitForReadline = 0;
        if(buf && buf[0] != '\0') {
          laxWaitForReadline = strtol(buf,NULL,10);
        }
        break;
      case 'z':
        clearPendingOnInterrupt = 1;
        if(buf) {
          clearPendingOnInterrupt = strtol(buf,NULL,10);
        }
        break;
      }
      continue;
    }

    int numBytes0=0,numBytes1=0,numBytesFifo=0,
        numBytesFdIn=0,numBytesFdOut=0;

    // write to these
    if(FD_ISSET(1,&writeSet)) {
      int numToWrite;
      if(toOutPos-toOutBuf+toOutSize < BUFSIZE) {
        numToWrite = toOutSize;
      } else {
        numToWrite = BUFSIZE - (toOutPos-toOutBuf);
      }
      numBytes = write(1,toOutPos,numToWrite);
      if(numBytes == -1) {
        error_at_line(0,errno,__FILE__,__LINE__,"write failed");continue; }
      if(outFd != -1) { // everything going to stdout also goes to outFd
        write(outFd,toOutPos,numBytes); // hope no error (don't reuse numBytes)
      }
      toOutSize -= numBytes;
      toOutPos += numBytes;
      if(toOutPos - toOutBuf >= BUFSIZE) {
        toOutPos -= BUFSIZE;
      }
//      printf("write to stdout %d bytes\r\nbase 0x%tx\r\n"
//             "pos  0x%tx toOutSize is now %d numToWrite %d\r\n",
//             numBytes, (ptrdiff_t)toOutBuf,
//             (ptrdiff_t)toOutPos,toOutSize,numToWrite);
      numBytes1 = numBytes;
    }
    if(FD_ISSET(fd,&writeSet)) {
      int numToWrite;
      if(toFdPos-toFdBuf+toFdSize < BUFSIZE) {
        numToWrite = toFdSize;
      } else {
        numToWrite = BUFSIZE - (toFdPos-toFdBuf);
      }
      if(pamperReadline) {
        int i;
        char *tmp=toFdPos;
        for(i=0;i<numToWrite;i++) {
          if(*tmp == '\r' || *tmp == '\n') {
            numToWrite = i+1;
//              write(1,"newline",strlen("newline"));
            waitForReadline = 1;
            break;
          }
          tmp++;
          if(tmp - toFdBuf >= BUFSIZE) {
            // not technically needed (range of numToWrite will not cross this)
            tmp -= BUFSIZE;
          }
        }
      }
      if(clearPending) {
        toFdSize = 0;
        clearPending = 0;
        if(debugfd != -1) {
          char buf = '\n';
          write(debugfd,&buf,1);
        }
        continue;
      }
      numBytes = write(fd,toFdPos,numToWrite);
      if(pamperReadline && numBytes != numToWrite) {
        waitForReadline = 0;
//        write(1,"unsetting waitForReadline",strlen("unsetting waitForReadline"));
      }
      if(numBytes == -1) {
        error_at_line(0,errno,__FILE__,__LINE__,"write failed");continue; }
      if(dumpFd != -1) { // duplicate traffic to terminal program in dumpFd
        write(dumpFd,toFdPos,numBytes); // hope no error (don't reuse numBytes)
      }
      toFdSize -= numBytes;
      toFdPos += numBytes;
      if(toFdPos - toFdBuf >= BUFSIZE) {
        toFdPos -= BUFSIZE;
      }
//      printf("write to fd %d bytes\r\nbase 0x%tx\r\n"
//             "pos  0x%tx toFdSize is now %d numToWrite %d\r\n",
//             numBytes, (ptrdiff_t)toFdBuf,
//             (ptrdiff_t)toFdPos,toFdSize,numToWrite);
      numBytesFdIn = numBytes;
    }

    // read from these
    if(FD_ISSET(0,&readSet)) {
      int numToRead;
      char *startPos;
      if(toFdPos-toFdBuf+toFdSize < BUFSIZE) {
        startPos = toFdPos+toFdSize;
        numToRead = BUFSIZE - (startPos - toFdBuf);
      } else {
        startPos = toFdPos+toFdSize-BUFSIZE;
        numToRead = BUFSIZE - toFdSize;
      }
      numBytes = read(0,startPos,numToRead);
      if(numBytes == -1) {
        error_at_line(0,errno,__FILE__,__LINE__,"read failed");continue; }
      toFdSize += numBytes;
//      printf("read from stdin %d bytes\r\nat   0x%tx\r\nbase 0x%tx\r\n"
//             "pos  0x%tx toFdSize is now %d numToRead %d\r\n",
//             numBytes,(ptrdiff_t)startPos, (ptrdiff_t)toFdBuf,
//             (ptrdiff_t)toFdPos,toFdSize,numToRead);
      numBytes0 = numBytes;
    }
    for(curFifo=0;curFifo<numFifo;curFifo++) {
      if(FD_ISSET(fifos[curFifo],&readSet)) {
        int numToRead;
        char *startPos;
        if(toFdPos-toFdBuf+toFdSize < BUFSIZE) {
          startPos = toFdPos+toFdSize;
          numToRead = BUFSIZE - (startPos - toFdBuf);
        } else {
          startPos = toFdPos+toFdSize-BUFSIZE;
          numToRead = BUFSIZE - toFdSize;
        }
        numBytes = read(fifos[curFifo],startPos,numToRead);
        if(numBytes == -1) {
          error_at_line(0,errno,__FILE__,__LINE__,"read failed");continue; }
        toFdSize += numBytes;
  //      printf("read from fifos[%d] %d bytes\r\nat   0x%tx\r\nbase 0x%tx\r\n"
  //             "pos  0x%tx toFdSize is now %d numToRead %d\r\n",curFifo,
  //             numBytes,(ptrdiff_t)startPos, (ptrdiff_t)toFdBuf,
  //             (ptrdiff_t)toFdPos,toFdSize,numToRead);
        numBytesFifo += numBytes;
      }
    }
    if(FD_ISSET(fd,&readSet)) {
      int numToRead;
      char *startPos;
      if(toOutPos-toOutBuf+toOutSize < BUFSIZE) {
        startPos = toOutPos+toOutSize;
        numToRead = BUFSIZE - (startPos - toOutBuf);
      } else {
        startPos = toOutPos+toOutSize-BUFSIZE;
        numToRead = BUFSIZE - toOutSize;
      }
      numBytes = read(fd,startPos,numToRead);
      if(pamperReadline && (waitForReadline || !onNormalPrompt)) {
        // need to look all the time when on a non-normal prompt since
        // we may not input a newline on a non-normal prompt and have
        // it transition to a normal prompt (think q given to less)
        int i;
        int curPrompt;
        for(curPrompt=0;curPrompt<numPrompts;curPrompt++) {
          if(*prompts[curPrompt] != '\0') {
            for(i=0;i<numBytes;i++) {
              if(*posInPrompts[curPrompt] == '\0') {
                posInPrompts[curPrompt] = prompts[curPrompt];
              }
              if(*posInPrompts[curPrompt] == startPos[i]) {
                posInPrompts[curPrompt]++;
              } else {
                posInPrompts[curPrompt] = prompts[curPrompt];
              }
            }
          }
        }
        int checkForMore = 0;
        int normal = 1;
        for(curPrompt=0;curPrompt<numPrompts;curPrompt++) {
          if(*posInPrompts[curPrompt] == '\0') {
            checkForMore = 1;
            normal = normal && normalPrompt[curPrompt];
          }
        }
        if(checkForMore || numPrompts <= 0) {
          // TODO this should really be rolled into the select in the main
          // loop so we can do other things instead of waiting in a sleep
          struct timespec ts;
          ts.tv_sec = 0;
//          ts.tv_nsec = 10000000; // 10ms
          ts.tv_nsec = 1000000; // 1ms
//          write(1,"waiting",strlen("waiting"));
          nanosleep(&ts,NULL);
          FD_ZERO(&readSet);
          FD_SET(fd,&readSet);
          tv.tv_sec = 0;
          tv.tv_usec = 0;
          ret = select(fd+1,&readSet,NULL,NULL,&tv);
          if(!FD_ISSET(fd,&readSet)) { // no more input available (on prompt)
            waitForReadline = 0;
            onNormalPrompt = normal;
//            if(onNormalPrompt) {
//              write(2,"normalPrompt",strlen("normalPrompt"));
//            } else {
//              write(2,"notNormalPrompt",strlen("notNormalPrompt"));
//            }
          }
        }
      }
//      if(numBytes == -1) {error_at_line(0,errno,__FILE__,__LINE__,"read failed");continue; }
      if(numBytes == -1) {break;} // usually pipe breaks before SIGCHLD
      toOutSize += numBytes;
//      printf("read from fd %d bytes\r\nat   0x%tx\r\nbase 0x%tx\r\n"
//             "pos  0x%tx toOutSize is now %d numToRead %d\r\n",
//             numBytes,(ptrdiff_t)startPos, (ptrdiff_t)toOutBuf,
//             (ptrdiff_t)toOutPos,toOutSize,numToRead);
      numBytesFdOut = numBytes;
    }

    if(debugfd != -1) {
      // TODO do the fifos right in the dump (instead of only first one)
      char buf[1024];
      int size;
      size = snprintf(buf,1024,
                      "fd%5d out%5d numBytes x:%d %d:x x:%d %d:%d\r\n",
                      toFdSize,toOutSize,
                      numBytes0,numBytes1,numBytesFifo,
                      numBytesFdIn,numBytesFdOut);
      write(debugfd,buf,size);
    }
  }

  if(debugfd != -1) {
    close(debugfd);
  }
  close(fd);
  for(curFifo=0;curFifo<numFifo;curFifo++) {
    close(fifos[curFifo]);
  }
  if(outFd != -1) {
    close(outFd);
  }
  if(dumpFd != -1) {
    close(dumpFd);
  }
  if(setTerm) {
    tcsetattr(0,TCSANOW,&origTermData);
  }

}
Esempio n. 9
0
/** Reads the command received and excecutes the corrisponding process sending it it's arguments and 
also responds to special characters.*/
int process_input(const char * input, int tty_number) { 

	int  piped = 0;
	char file_call_buffer[1024];
	char stdout_call_buffer[128];
	char stdin_call_buffer[128];
	
	int stdout_file = 0;
	int stdin_file = 0;
	int read_ptr = 0;
	int stdin = 0;
	int stdout = 0;
	do {
		int i = 0;
		int write_i = 0;
		for(; i < 128; ++i) {
			stdout_call_buffer[i] = 0;
			stdin_call_buffer[i]  = 0;
		}

		for(i = 0; i < 1024; ++i)	{
			file_call_buffer[i] = 0;
		}
		i = read_ptr;
		
		char * file_call;

		
		int valid_input = 0;
		char * current_buffer = file_call_buffer;
		for(; input[i] && input[i] != '|'; ++i) {
			if(strlen(current_buffer) > 0 ) {
				if(input[i] == '>') {
					current_buffer = stdout_call_buffer;
					valid_input = 0;
					write_i = 0;
					stdout_file = 1;

					continue;
				} else if (input[i] == '<') { 
					current_buffer = stdin_call_buffer;
					valid_input = 0;
					write_i = 0;
					stdin_file = 1;
					continue;
				}
			} else {
				if (input[i] == '>' || input[i] == '<') {
					return 0;
				}
			}
			valid_input = input[i] != ' ';
			if(!(write_i == 0 && !valid_input)) {
				current_buffer[write_i++] = input[i];
			}
		}
		if(i == 0 && input[i] == '|') {
			return 0;
		}
		piped = (input[i] == '|') && !stdin_file && !stdout_file; 
		i++;
		
		if(piped)
		{
			read_ptr = i;
		}
		
		int n = 0;
		char** strs = split_string(file_call_buffer, ' ', &n);
		
		
		int pid = pcreate(strs[0], n, strs);
		
		if(pid != -1)
		{
			if(stdout_file) {
				int _stdout = open(stdout_call_buffer, O_WR | O_NEW);
				if(_stdout >= 0)
				{
					pdup2(pid, _stdout, STDOUT);
 				} else {
					printf("TTY: file %s could not be opened for output, invalid perms?\n", stdout_call_buffer);
				}
			}
			
			if(stdin_file) {
				int _stdin = open(stdin_call_buffer, O_RD);
				if(_stdin >= 0)
				{
					pdup2(pid, _stdin, STDIN);
				} else {
					printf("TTY: file %s could not be opened for input, invalid perms?\n", stdin_call_buffer);
				}

			}
			
			// For pipe
			if(stdin)	{
				pdup2(pid, stdin, STDIN);
			}
			char cad[20];
			if(piped)
			{
				cad[0] = '.';
				itoa(pid, cad + 1);
				stdout = mkfifo(cad, 0600);
				pdup2(pid,stdout,STDOUT);
				stdin = stdout;
				stdout = 0;
			}
			
			prun(pid);
			if(!string_ends_with(file_call_buffer, '&') && !piped) {
				waitpid(pid);
				rm(cad);
			}
		}
	} while(piped);
	return 1;
}
Esempio n. 10
0
int writeFIFO(int in)
{
    const char *fifo_name = "/tmp/my_fifo";
    int pipe_fd = -1;
    int data_fd = -1;
    int res = 0;
    const int open_mode = O_WRONLY;
    int bytes_sent = 0;
    char buffer[PIPE_BUF + 1];
    int bytes_read = 0;

    if(access(fifo_name, F_OK) == -1)
    {
        printf ("Create the fifo pipe.\n");
        res = mkfifo(fifo_name, 0777);

        if(res != 0)
        {
            fprintf(stderr, "Could not create fifo %s\n", fifo_name);
            exit(EXIT_FAILURE);
        }
    }

    if(in != -1)
    {
        std::ofstream file;
        file.open("Data.txt");
        file<<in;
        file.close();
    }
    printf("Process %d opening FIFO O_WRONLY\n", getpid());
    pipe_fd = open(fifo_name, open_mode);
    printf("Process %d result %d\n", getpid(), pipe_fd);

    if(pipe_fd != -1)
    {
        bytes_read = 0;
        data_fd = open("Data.txt", O_RDONLY);
        if (data_fd == -1)
        {
            close(pipe_fd);
            fprintf (stderr, "Open file[Data.txt] failed\n");
            return -1;
        }

        bytes_read = read(data_fd, buffer, PIPE_BUF);
        buffer[bytes_read] = '\0';
        while(bytes_read > 0)
        {

            res = write(pipe_fd, buffer, bytes_read);
            if(res == -1)
            {
                fprintf(stderr, "Write error on pipe\n");
                exit(EXIT_FAILURE);
            }

            bytes_sent += res;
            bytes_read = read(data_fd, buffer, PIPE_BUF);
            buffer[bytes_read] = '\0';
        }

        close(pipe_fd);
        close(data_fd);
    }
    else
        exit(EXIT_FAILURE);

    printf("Process %d finished\n", getpid());
    return 1;
}
Esempio n. 11
0
bool create_pipe(char* path) {
	if (mkfifo(path,0666) != 0) {
		if (errno != EEXIST) return false;
	}
	return true;
}
Esempio n. 12
0
int main(int argc, char *argv[]) {
	const char *code = argv[1];
	const char *slash = strrchr(code, '/');

	int ret;

	/* stupid automake! */
	if (slash)
		code = slash + 1;

	if (code[0] == '_') {
		struct stat st;
		if (lstat(INPUT_FILE, &st))
			return 77;

		switch (code[1]) {
			case T_BROKEN_SYMLINK:
				ex_linkdest[0]++;
		}
	} else {
		/* XXX: replace tests */
		unlink(INPUT_FILE);
		unlink(OUTPUT_FILE);

		switch (code[0]) {
			case T_REGULAR:
			case T_EMPTY:
				if (!create_input(INPUT_FILE, code[0] == T_REGULAR)) {
					perror("Input creation failed");
					return 2;
				}
				break;
			case T_BROKEN_SYMLINK:
				ex_linkdest[0]++;
			case T_SYMLINK:
				if (symlink(ex_linkdest, INPUT_FILE)) {
					perror("Input symlink creation failed");
					return 77;
				}
				break;
			case T_NAMED_PIPE:
				if (mkfifo(INPUT_FILE, 0700)) {
					perror("Named pipe creation failed");
					return 77;
				}
				break;
			case T_BLK_DEV:
#ifdef S_IFBLK
				if (mknod(INPUT_FILE, 0700 | S_IFBLK, 0xff00)) {
					perror("Block device creation failed");
					return 77;
				}
#else
				fprintf(stderr, "Block devices not supported\n");
				return 77;
#endif
				break;
			case T_CHR_DEV:
#ifdef S_IFCHR
				if (mknod(INPUT_FILE, 0700 | S_IFCHR, 0x0103)) {
					perror("Character device creation failed");
					return 77;
				}
#else
				fprintf(stderr, "Character devices not supported\n");
				return 77;
#endif
				break;
			default:
				fprintf(stderr, "Invalid arg: [%s]\n", code);
				return 3;
		}
	}

	ret = ai_cp_a(INPUT_FILE, OUTPUT_FILE);
	if (ret) {
		fprintf(stderr, "[%s] Copying failed: %s\n",
				code, strerror(errno));
		return 1;
	}

	return compare_files(INPUT_FILE, OUTPUT_FILE, code);
}
Esempio n. 13
0
/**
 * Initialization of data structures for running under a debugger
 * using an extended MPICH/TotalView parallel debugger interface.  Before the
 * spawn we need to check if we are being run under a TotalView-like
 * debugger; if so then inform applications via an MCA parameter.
 */
void init_before_spawn(orte_job_t *jdata)
{
    char *env_name;
    orte_app_context_t *app;
    int i;
    int32_t ljob;
    char *attach_fifo;

    if (!MPIR_being_debugged && !orte_in_parallel_debugger) {
        /* if we were given a test debugger, then we still want to
         * colaunch it
         */
        if (NULL != orte_debugger_base.test_daemon) {
            opal_output_verbose(2, orte_debugger_base.output,
                                "%s No debugger test daemon specified",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME));
            goto launchit;
        }
        /* if we were given an auto-detect rate, then we want to setup
         * an event so we periodically do the check
         */
        if (0 < orte_debugger_mpirx_check_rate) {
            opal_output_verbose(2, orte_debugger_base.output,
                                "%s Setting debugger attach check rate for %d seconds",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                                orte_debugger_mpirx_check_rate);
            ORTE_TIMER_EVENT(orte_debugger_mpirx_check_rate, 0, attach_debugger);
        } else {
            /* create the attachment FIFO and put it into MPIR, setup readevent */
            /* create a FIFO name in the session dir */
            attach_fifo = opal_os_path(false, orte_process_info.job_session_dir, "debugger_attach_fifo", NULL);
            if ((mkfifo(attach_fifo, FILE_MODE) < 0) && errno != EEXIST) {
                opal_output(0, "CANNOT CREATE FIFO %s: errno %d", attach_fifo, errno);
                free(attach_fifo);
                return;
            }
            strncpy(MPIR_attach_fifo, attach_fifo, MPIR_MAX_PATH_LENGTH - 1);
	    free (attach_fifo);
	    open_fifo ();
        }
        return;
    }
    
 launchit:
    opal_output_verbose(2, orte_debugger_base.output,
                        "%s: Spawned by a debugger",
                        ORTE_NAME_PRINT(ORTE_PROC_MY_NAME));

    /* tell the procs they are being debugged */
    env_name = mca_base_param_environ_variable("orte", 
                                               "in_parallel_debugger", NULL);
    
    for (i=0; i < jdata->apps->size; i++) {
        if (NULL == (app = (orte_app_context_t*)opal_pointer_array_get_item(jdata->apps, i))) {
            continue;
        }
        opal_setenv(env_name, "1", true, &app->env);
    }
    free(env_name);

    /* check if we need to co-spawn the debugger daemons */
    if ('\0' != MPIR_executable_path[0] || NULL != orte_debugger_base.test_daemon) {
        /* can only have one debugger */
        if (NULL != orte_debugger_daemon) {
            opal_output(0, "-------------------------------------------\n"
                        "Only one debugger can be used on a job.\n"
                        "-------------------------------------------\n");
            ORTE_UPDATE_EXIT_STATUS(ORTE_ERROR_DEFAULT_EXIT_CODE);
            return;
        }
        opal_output_verbose(2, orte_debugger_base.output,
                            "%s Cospawning debugger daemons %s",
                            ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                            (NULL == orte_debugger_base.test_daemon) ?
                            MPIR_executable_path : orte_debugger_base.test_daemon);
        /* add debugger info to launch message */
        orte_debugger_daemon = OBJ_NEW(orte_job_t);
        /* create a jobid for these daemons - this is done solely
         * to avoid confusing the rest of the system's bookkeeping
         */
        orte_plm_base_create_jobid(orte_debugger_daemon);
        /* flag the job as being debugger daemons */
        orte_debugger_daemon->controls |= ORTE_JOB_CONTROL_DEBUGGER_DAEMON;
        /* unless directed, we do not forward output */
        if (!MPIR_forward_output) {
            orte_debugger_daemon->controls &= ~ORTE_JOB_CONTROL_FORWARD_OUTPUT;
        }
        /* add it to the global job pool */
        ljob = ORTE_LOCAL_JOBID(orte_debugger_daemon->jobid);
        opal_pointer_array_set_item(orte_job_data, ljob, orte_debugger_daemon);
        /* create an app_context for the debugger daemon */
        app = OBJ_NEW(orte_app_context_t);
        if (NULL != orte_debugger_base.test_daemon) {
            app->app = strdup(orte_debugger_base.test_daemon);
        } else {
            app->app = strdup((char*)MPIR_executable_path);
        }
        opal_argv_append_nosize(&app->argv, app->app);
        build_debugger_args(app);
        opal_pointer_array_add(orte_debugger_daemon->apps, app);
        orte_debugger_daemon->num_apps = 1;
    }
    return;
}
Esempio n. 14
0
int main(){
	//создаем именованные каналы в ядре с местом в файловом пространстве имен
	printf("Создаю именованные каналы...");fflush(stdout);
	const char *pipe_in="in.fifo", *pipe_out="out.fifo";
	unlink(pipe_in);
	unlink(pipe_out);
	int res=mkfifo(pipe_in,0666);
	if(-1==res){
		perror("Ошибка создания канала in");
		return 1;
	}
	res=mkfifo(pipe_out,0666);
	if(-1==res){
		perror("Ошибка создания канала out");
		return 2;
	}
	printf("ok!\n");

	//получаем файловые дескрипторы каналов и переводим в неблокирующий режим (чтение и запись, чтоб не блокировалось здесь же сразу)
	printf("Получаю файловые дескрипторы...");
	int fd_in=open(pipe_in,O_RDWR|O_NONBLOCK);
	if(-1==fd_in){
		perror("Не получен дескриптор in");
		return 3;
	}
	int fd_out=open(pipe_out,O_RDWR|O_NONBLOCK);
	if(-1==fd_out){
		perror("Не получен дескриптор out");
		close(fd_in);
		return 4;
	}
	printf("ok!\n");

	//мультиплексирование
	printf("Мультиплексирование (select):\n");
	fd_set set_for_read, set_for_write;    //ровно по 1024 бит 
	printf("Цикл:\n");
	//узнаем наибольший номер дескриптора, чтоб узнать сколько битов в наборе нужно отслеживать
	int max=fd_in<fd_out ? fd_out : fd_in;
	//буфер на сервере (на случай задержки отправки)
	struct Buf *root=NULL, *tail=NULL;
	int is_out=0;
	//запускаем цикл проверки
	long long cnt=0;
	while(1){
		//инициализация
		FD_ZERO(&set_for_read); 
		FD_ZERO(&set_for_write);
		
		//добавляем в набор отслеживаемый на чтение дескриптор
		printf("\tдобавляем in...");
		FD_SET(fd_in,&set_for_read);
		printf("ok!\n");
		if(is_out){
			printf("\tдобавляем out...");
			FD_SET(fd_out,&set_for_write);
			printf("ok!\n");
		}
	        fflush(stdout);

		//запускаем проверку готовности
		++cnt;
		printf("\n%lld)-->select...",cnt);fflush(stdout);
		select(max+1,&set_for_read,&set_for_write,NULL,NULL);//эта команда сбрасывает не готовые биты поля, поэтому нужно регистрировать поновой	
		printf("ok!\n");
		//проснулись
		if(FD_ISSET(fd_out,&set_for_write)){ //проверка готовности писать
			printf("-->write...");
			if(root==NULL)
				FD_CLR(fd_out,&set_for_write);//снимаем с регистрации, т.к. нечего писать
			else{
				int len=write(fd_out,root->data,root->len);
				if(len!=-1){//успешно записано
					printf("ok!\n");
					struct Buf * tmp=root->next;
					free(root);
					root=tmp;
					if(root==NULL){ //все записано
						tail=NULL;
						is_out=0;
					}
				}
			}
		}
		if(FD_ISSET(fd_in,&set_for_read)){ //проверка готовности чтения
			printf("-->read...");
			//читаем из канала
			char data[LEN+1];
			int len=read(fd_in,data,LEN);
			if(-1!=len){
				if(root==NULL)
					tail=root=(struct Buf*)malloc(sizeof(struct Buf));
				else{
					tail->next=(struct Buf*)malloc(sizeof(struct Buf));
					tail=tail->next;
				}
				tail->next=NULL;
				tail->len=len;
				memcpy(tail->data,data,len);
				data[len]='\0';
				printf("ok! data=%s\n",data);

				//регистрируем дескриптор out
				is_out=1;
			}

		}
	}

	//закрываем дескрипторы
	close(fd_in);
	close(fd_out);

	//выносим каналы из фалового пространства
	unlink(pipe_in);
	unlink(pipe_out);
	
	return 0;
}
Esempio n. 15
0
int main(int argc, char* argv[])
{
	char c;
	int i;
	time(&timer);//系统开始的时间
	initFile();
	if (!(ptr_auxMem = fopen(AUXILIARY_MEMORY, "r+")))
	{
		do_error(ERROR_FILE_OPEN_FAILED);
		exit(1);
	}
	
	do_init();
	do_print_info();

	ptr_memAccReq = (Ptr_MemoryAccessRequest) malloc(sizeof(MemoryAccessRequest));
///////////////////////////在main中创建管道
	struct stat statbuf;
	int fifo;
	if(stat("/tmp/vmm",&statbuf)==0)
	{
		/* 如果FIFO文件存在,删掉 */
		if(remove("/tmp/vmm")<0)
		{
			perror("remove failed");
			exit(1);
		}
	}

	if(mkfifo("/tmp/vmm",0666)<0)
	{
		perror("mkfifo failed");
		exit(1);
	}
	if((fifo=open("/tmp/vmm",O_RDONLY))<0)
	{
		perror("open failed");
		exit(1);
	}
	
	/* 在循环中模拟访存请求与处理过程 */
	while (TRUE)
	{
		//do_request();
		if((read(fifo,ptr_memAccReq,sizeof(MemoryAccessRequest)))<0)
		{
			perror("read failed");
			exit(1);
		}//读管道内容
		do_response();
		/////////
		time(&timerc);
		if((timerc-timer)>=Time)//经过一定时间,更新页面老化算法的计数器
		{
			for(i = 0; i < PAGE_SUM; i++)
			{
				pageTable[i].count_1=(pageTable[i].count_1>>1)|(pageTable[i].R<<31);
				pageTable[i].R=0;
			}
			timer=timerc;
		}
		printf("按1打印页表,按2打印页表和实存内容,按3打印页表、辅存和实存内容,按其他键不打印...\n");
		if ((c = getchar()) == '1')
			do_print_info();
		if (c== '2')
		{
			do_print_info();
			do_print_actMem();
		}
		if (c== '3')
		{
			do_print_info();
			do_print_actMem();
			do_print_auxMem();
		}
		while (c != '\n')
			c = getchar();
		printf("按X退出程序,按其他键继续...\n");
		if ((c = getchar()) == 'x' || c == 'X')
			break;
		while (c != '\n')
			c = getchar();
		//sleep(5000);
	}

	if (fclose(ptr_auxMem) == EOF)
	{
		do_error(ERROR_FILE_CLOSE_FAILED);
		exit(1);
	}
	close(fifo);
	return (0);
}
Esempio n. 16
0
int
main_mknod(rtems_shell_mknod_globals* globals, int argc, char **argv)
{
	char	*name, *p;
	mode_t	 mode;
	portdev_t	 dev;
	pack_t	*pack;
	u_long	 numbers[MAXARGS];
	int	 n, ch, fifo, hasformat;
	int	 r_flag = 0;		/* force: delete existing entry */
#ifdef KERN_DRIVERS
	int	 l_flag = 0;		/* list device names and numbers */
	int	 major;
#endif
#if RTEMS_REMOVED
	void	*modes = 0;
#endif
	uid_t	 uid = -1;
	gid_t	 gid = -1;
	int	 rval;

	struct getopt_data getopt_reent;
	memset(&getopt_reent, 0, sizeof(getopt_data));

	dev = 0;
	fifo = hasformat = 0;
	pack = pack_native;

#ifdef KERN_DRIVERS
	while ((ch = getopt(argc, argv, "lrRF:g:m:u:")) != -1) {
#else
	while ((ch = getopt_r(argc, argv, "rRF:g:m:u:", &getopt_reent)) != -1) {
#endif
		switch (ch) {

#ifdef KERN_DRIVERS
		case 'l':
			l_flag = 1;
			break;
#endif

		case 'r':
			r_flag = 1;
			break;

		case 'R':
			r_flag = 2;
			break;

		case 'F':
			pack = pack_find(getopt_reent.optarg);
			if (pack == NULL)
				errx(exit_jump, 1, "invalid format: %s", getopt_reent.optarg);
			hasformat++;
			break;

		case 'g':
			if (getopt_reent.optarg[0] == '#') {
				gid = strtol(getopt_reent.optarg + 1, &p, 10);
				if (*p == 0)
					break;
			}
			if (gid_name(getopt_reent.optarg, &gid) == 0)
				break;
			gid = strtol(getopt_reent.optarg, &p, 10);
			if (*p == 0)
				break;
			errx(exit_jump, 1, "%s: invalid group name", getopt_reent.optarg);

		case 'm':
#if RTEMS_REMOVED
			modes = setmode(getopt_reent.optarg);
			if (modes == NULL)
#endif
				err(exit_jump, 1, "Cannot set file mode `%s'", getopt_reent.optarg);
			break;

		case 'u':
			if (getopt_reent.optarg[0] == '#') {
				uid = strtol(getopt_reent.optarg + 1, &p, 10);
				if (*p == 0)
					break;
			}
#if RTEMS_REMOVED
			if (uid_from_user(getopt_reent.optarg, &uid) == 0)
				break;
#endif
			uid = strtol(getopt_reent.optarg, &p, 10);
			if (*p == 0)
				break;
			errx(exit_jump, 1, "%s: invalid user name", getopt_reent.optarg);

		default:
		case '?':
			usage(globals);
		}
	}
	argc -= getopt_reent.optind;
	argv += getopt_reent.optind;

#ifdef KERN_DRIVERS
	if (l_flag) {
		print_device_info(argv);
		return 0;
	}
#endif

	if (argc < 2 || argc > 10)
		usage(globals);

	name = *argv;
	argc--;
	argv++;

	umask(mode = umask(0));
	mode = (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) & ~mode;

	if (argv[0][1] != '\0')
		goto badtype;
	switch (*argv[0]) {
	case 'c':
		mode |= S_IFCHR;
		break;

	case 'b':
		mode |= S_IFBLK;
		break;

	case 'p':
		if (hasformat)
			errx(exit_jump, 1, "format is meaningless for fifos");
		mode |= S_IFIFO;
		fifo = 1;
		break;

	default:
 badtype:
		errx(exit_jump, 1, "node type must be 'b', 'c' or 'p'.");
	}
	argc--;
	argv++;

	if (fifo) {
		if (argc != 0)
			usage(globals);
	} else {
		if (argc < 1 || argc > MAXARGS)
			usage(globals);
	}

	for (n = 0; n < argc; n++) {
		errno = 0;
		numbers[n] = strtoul(argv[n], &p, 0);
		if (*p == 0 && errno == 0)
			continue;
#ifdef KERN_DRIVERS
		if (n == 0) {
			major = major_from_name(argv[0], mode);
			if (major != -1) {
				numbers[0] = major;
				continue;
			}
			if (!isdigit(*(unsigned char *)argv[0]))
				errx(1, "unknown driver: %s", argv[0]);
		}
#endif
		errx(exit_jump, 1, "invalid number: %s", argv[n]);
	}

	switch (argc) {
	case 0:
		dev = 0;
		break;

	case 1:
		dev = numbers[0];
		break;

	default:
		dev = callPack(globals, pack, argc, numbers);
		break;
	}

#if RTEMS_REMOVED
	if (modes != NULL)
		mode = getmode(modes, mode);
#endif
	umask(0);
	rval = fifo ? mkfifo(name, mode) : mknod(name, mode, dev);
	if (rval < 0 && errno == EEXIST && r_flag) {
		struct stat sb;
		if (lstat(name, &sb) != 0 || (!fifo && sb.st_rdev != dev))
			sb.st_mode = 0;

		if ((sb.st_mode & S_IFMT) == (mode & S_IFMT)) {
			if (r_flag == 1)
				/* Ignore permissions and user/group */
				return 0;
			if (sb.st_mode != mode)
				rval = chmod(name, mode);
			else
				rval = 0;
		} else {
			unlink(name);
			rval = fifo ? mkfifo(name, mode)
				    : mknod(name, mode, dev);
		}
	}
	if (rval < 0)
		err(exit_jump, 1, "%s", name);
	if ((uid != (uid_t)-1 || gid != (uid_t)-1) && chown(name, uid, gid) == -1)
		/* XXX Should we unlink the files here? */
		warn("%s: uid/gid not changed", name);

	return 0;
}

static void
usage(rtems_shell_mknod_globals* globals)
{
	const char *progname = getprogname();

	(void)fprintf(stderr,
	    "usage: %s [-rR] [-F format] [-m mode] [-u user] [-g group]\n",
	    progname);
	(void)fprintf(stderr,
#ifdef KERN_DRIVERS
	    "                   [ name [b | c] [major | driver] minor\n"
#else
	    "                   [ name [b | c] major minor\n"
#endif
	    "                   | name [b | c] major unit subunit\n"
	    "                   | name [b | c] number\n"
	    "                   | name p ]\n");
#ifdef KERN_DRIVERS
	(void)fprintf(stderr, "       %s -l [driver] ...\n", progname);
#endif
	exit(1);
}

static int
gid_name(const char *name, gid_t *gid)
{
	struct group *g;

	g = getgrnam(name);
	if (!g)
		return -1;
	*gid = g->gr_gid;
	return 0;
}

static portdev_t
callPack(rtems_shell_mknod_globals* globals, pack_t *f, int n, u_long *numbers)
{
	portdev_t d;
	const char *error = NULL;

	d = (*f)(n, numbers, &error);
	if (error != NULL)
		errx(exit_jump, 1, "%s", error);
	return d;
}
Esempio n. 17
0
static int
do_test (void)
{
  int ret = 0;
  static const char *fifo_name = "some-fifo";

  size_t filenamelen = strlen (dirbuf) + strlen (fifo_name) + 2;
  char *filename = xmalloc (filenamelen);

  snprintf (filename, filenamelen, "%s/%s", dirbuf, fifo_name);

  /* Create a fifo in the directory.  */
  int e = mkfifo (filename, 0777);
  if (e == -1)
    {
      printf ("fifo creation failed (%s)\n", strerror (errno));
      ret = 1;
      goto out_nofifo;
    }

  long dir_pathconf = pathconf (dirbuf, _PC_PIPE_BUF);

  if (dir_pathconf < 0)
    {
      printf ("pathconf on directory failed: %s\n", strerror (errno));
      ret = 1;
      goto out_nofifo;
    }

  long fifo_pathconf = pathconf (filename, _PC_PIPE_BUF);

  if (fifo_pathconf < 0)
    {
      printf ("pathconf on file failed: %s\n", strerror (errno));
      ret = 1;
      goto out_nofifo;
    }

  int fifo = open (filename, O_RDONLY | O_NONBLOCK);

  if (fifo < 0)
    {
      printf ("fifo open failed (%s)\n", strerror (errno));
      ret = 1;
      goto out_nofifo;
    }

  long dir_fpathconf = fpathconf (dir_fd, _PC_PIPE_BUF);

  if (dir_fpathconf < 0)
    {
      printf ("fpathconf on directory failed: %s\n", strerror (errno));
      ret = 1;
      goto out;
    }

  long fifo_fpathconf = fpathconf (fifo, _PC_PIPE_BUF);

  if (fifo_fpathconf < 0)
    {
      printf ("fpathconf on file failed: %s\n", strerror (errno));
      ret = 1;
      goto out;
    }

  if (fifo_pathconf != fifo_fpathconf)
    {
      printf ("fifo pathconf (%ld) != fifo fpathconf (%ld)\n", fifo_pathconf,
	      fifo_fpathconf);
      ret = 1;
      goto out;
    }

  if (dir_pathconf != fifo_pathconf)
    {
      printf ("directory pathconf (%ld) != fifo pathconf (%ld)\n",
	      dir_pathconf, fifo_pathconf);
      ret = 1;
      goto out;
    }

  if (dir_fpathconf != fifo_fpathconf)
    {
      printf ("directory fpathconf (%ld) != fifo fpathconf (%ld)\n",
	      dir_fpathconf, fifo_fpathconf);
      ret = 1;
      goto out;
    }

out:
  close (fifo);
out_nofifo:
  close (dir_fd);

  if (unlink (filename) != 0)
    {
      printf ("Could not remove fifo (%s)\n", strerror (errno));
      ret = 1;
    }

  return ret;
}
Esempio n. 18
0
int main(int argc, char *argv[]) {

    static struct option long_opts[] = {
        {"help",   0, NULL, 'h'},
        {0,0,0,0}
    };
    int opt, opti;
    while ((opt=getopt_long(argc,argv,"h",long_opts,&opti))!=-1) {
        switch (opt) {
            default:
            case 'h':
                usage();
                exit(0);
                break;
        }
    }
    
    prctl(PR_SET_PDEATHSIG,SIGTERM); /* Ensure that if parent (the manager) dies, to kill this child too. */

    /* Create FIFO */
    int rv = mkfifo(vegas_DAQ_CONTROL, 0666);
    if (rv!=0 && errno!=EEXIST) {
        fprintf(stderr, "vegas_daq_server: Error creating control fifo\n");
        perror("mkfifo");
        exit(1);
    }

    /* Open command FIFO for read */
#define MAX_CMD_LEN 1024
    char cmd[MAX_CMD_LEN];
    int command_fifo;
    command_fifo = open(vegas_DAQ_CONTROL, O_RDONLY | O_NONBLOCK);
    if (command_fifo<0) {
        fprintf(stderr, "vegas_daq_server: Error opening control fifo\n");
        perror("open");
        exit(1);
    }

    /* Attach to shared memory buffers */
    struct vegas_status stat;
    struct vegas_databuf *dbuf_net=NULL, *dbuf_pfb=NULL, *dbuf_acc=NULL;
    rv = vegas_status_attach(&stat);
    const int netbuf_id = 1;
    const int pfbbuf_id = 2;
    const int accbuf_id = 3;
    if (rv!=VEGAS_OK) {
        fprintf(stderr, "Error connecting to vegas_status\n");
        exit(1);
    }
    dbuf_net = vegas_databuf_attach(netbuf_id);
    if (dbuf_net==NULL) {
        fprintf(stderr, "Error connecting to vegas_databuf (raw net)\n");
        exit(1);
    }
    vegas_databuf_clear(dbuf_net);
    dbuf_pfb = vegas_databuf_attach(pfbbuf_id);
    if (dbuf_pfb==NULL) {
        fprintf(stderr, "Error connecting to vegas_databuf (accum input)\n");
        exit(1);
    }
    vegas_databuf_clear(dbuf_pfb);

    dbuf_acc = vegas_databuf_attach(accbuf_id);
    if (dbuf_acc==NULL) {
        fprintf(stderr, "Error connecting to vegas_databuf (accum output)\n");
        exit(1);
    }
    vegas_databuf_clear(dbuf_acc);

    /* Thread setup */
#define MAX_THREAD 8
    int i;
    int nthread_cur = 0;
    struct vegas_thread_args args[MAX_THREAD];
    pthread_t thread_id[MAX_THREAD];
    for (i=0; i<MAX_THREAD; i++) thread_id[i] = 0;

    /* Print start time for logs */
    time_t curtime = time(NULL);
    char tmp[256];
    printf("\nvegas_daq_server started at %s", ctime_r(&curtime,tmp));
    fflush(stdout);

    /* hmm.. keep this old signal stuff?? */
    run=1;
    srv_run=1;
    signal(SIGINT, srv_cc);
    signal(SIGTERM, srv_quit);

    /* Loop over recv'd commands, process them */
    int cmd_wait=1;
    while (cmd_wait && srv_run) {

        // Check to see if threads have exited, if so, stop them
        if (check_thread_exit(args, nthread_cur)) {
            run = 0;
            stop_threads(args, thread_id, nthread_cur);
            nthread_cur = 0;
        }

        // Heartbeat, status update
        time_t curtime;
        char timestr[32];
        char *ctmp;
        time(&curtime);
        ctime_r(&curtime, timestr);
        ctmp = strchr(timestr, '\n');
        if (ctmp!=NULL) { *ctmp = '\0'; } else { timestr[0]='\0'; }
        vegas_status_lock(&stat);
        hputs(stat.buf, "DAQPULSE", timestr);
        hputs(stat.buf, "DAQSTATE", nthread_cur==0 ? "stopped" : "running");
        vegas_status_unlock(&stat);

        // Flush any status/error/etc for logfiles
        fflush(stdout);
        fflush(stderr);

        // Wait for data on fifo
        struct pollfd pfd;
        pfd.fd = command_fifo;
        pfd.events = POLLIN;
        rv = poll(&pfd, 1, 1000);
        if (rv==0) { continue; }
        else if (rv<0) {
            if (errno!=EINTR) perror("poll");
            continue;
        }

        // If we got POLLHUP, it means the other side closed its
        // connection.  Close and reopen the FIFO to clear this
        // condition.  Is there a better/recommended way to do this?
        if (pfd.revents==POLLHUP) { 
            close(command_fifo);
            command_fifo = open(vegas_DAQ_CONTROL, O_RDONLY | O_NONBLOCK);
            if (command_fifo<0) {
                fprintf(stderr, 
                        "vegas_daq_server: Error opening control fifo\n");
                perror("open");
                break;
            }
            continue;
        }

        // Read the command
        memset(cmd, 0, MAX_CMD_LEN);
        rv = read(command_fifo, cmd, MAX_CMD_LEN-1);
        if (rv==0) { continue; }
        else if (rv<0) {
            if (errno==EAGAIN) { continue; }
            else { perror("read");  continue; }
        } 

        // Truncate at newline
        // TODO: allow multiple commands in one read?
        char *ptr = strchr(cmd, '\n');
        if (ptr!=NULL) *ptr='\0'; 

        // Process the command 
        if (strncasecmp(cmd,"QUIT",MAX_CMD_LEN)==0) {
            // Exit program
            printf("Exit\n");
            run = 0;
            stop_threads(args, thread_id, nthread_cur);
            cmd_wait=0;
            continue;
        } 
        
        else if (strncasecmp(cmd,"START",MAX_CMD_LEN)==0 ||
                strncasecmp(cmd,"MONITOR",MAX_CMD_LEN)==0) {
            // Start observations
            // TODO : decide how to behave if observations are running
            printf("Start observations\n");

            if (nthread_cur>0) {
                printf("  observations already running!\n");
            } else {

                // Figure out which mode to start
                char obs_mode[32];
                if (strncasecmp(cmd,"START",MAX_CMD_LEN)==0) {
                    vegas_status_lock(&stat);
                    vegas_read_obs_mode(stat.buf, obs_mode);
                    vegas_status_unlock(&stat);
                } else {
                    strncpy(obs_mode, cmd, 32);
                }
                printf("  obs_mode = %s\n", obs_mode);

                // Clear out data bufs
                vegas_databuf_clear(dbuf_net);
                vegas_databuf_clear(dbuf_pfb);
                vegas_databuf_clear(dbuf_acc);


                // Do it
                run = 1;
                if (strncasecmp(obs_mode, "HBW", 4)==0) {
                    hputs(stat.buf, "BW_MODE", "high");
                    hputs(stat.buf, "SWVER", "1.4");
                    init_hbw_mode(args, &nthread_cur);
                    start_hbw_mode(args, thread_id);
                } else if (strncasecmp(obs_mode, "LBW", 4)==0) {
                    hputs(stat.buf, "BW_MODE", "low");
                    hputs(stat.buf, "SWVER", "1.4");

                    init_lbw_mode(args, &nthread_cur);
                    start_lbw_mode(args, thread_id);
                } else if (strncasecmp(obs_mode, "MONITOR", 8)==0) {
                    init_monitor_mode(args, &nthread_cur);
                    start_monitor_mode(args, thread_id);
                } else {
                    printf("  unrecognized obs_mode!\n");
                }

            }

        } 
        
        else if (strncasecmp(cmd,"STOP",MAX_CMD_LEN)==0) {
            // Stop observations
            printf("Stop observations\n");
            run = 0;
            stop_threads(args, thread_id, nthread_cur);
            nthread_cur = 0;
        } 
        
        else {
            // Unknown command
            printf("Unrecognized command '%s'\n", cmd);
        }
    }

    /* Stop any running threads */
    run = 0;
    stop_threads(args, thread_id, nthread_cur);

    if (command_fifo>0) close(command_fifo);

    vegas_status_lock(&stat);
    hputs(stat.buf, "DAQSTATE", "exiting");
    vegas_status_unlock(&stat);

    curtime = time(NULL);
    printf("vegas_daq_server exiting cleanly at %s\n", ctime_r(&curtime,tmp));

    fflush(stdout);
    fflush(stderr);

    /* TODO: remove FIFO */

    exit(0);
}
Esempio n. 19
0
void
main(int argc, char **argv)
{
    const char *connect_file = DEFAULT_CONNECT_FILE;
    int server_fifo;
    const char *dir;
    char c2s[1000], s2c[1000], connect[2010];
    int pid = getpid();
    int rfd, wfd;
    int use_home_dir = 0;
    char *prog_name = argv[0];

    while (--argc && **(++argv) == '-') {
	switch ((*argv)[1]) {
	case 'h':
	    use_home_dir = 1;
	    break;

	default:
	    goto usage;
	}
    }

    if (argc == 1)
	connect_file = argv[0];
    else if (argc != 0)
	goto usage;

    signal(SIGTERM, kill_signal);
    signal(SIGINT, kill_signal);
    signal(SIGQUIT, kill_signal);

    if (!use_home_dir || !(dir = getenv("HOME")))
	dir = "/usr/tmp";

    sprintf(c2s, "%s/.c2s-%05d", dir, (int) pid);
    sprintf(s2c, "%s/.s2c-%05d", dir, (int) pid);

    if (mkfifo(c2s, 0000) < 0 || chmod(c2s, 0644) < 0
	|| mkfifo(s2c, 0000) < 0 || chmod(s2c, 0622) < 0) {
	perror("Creating personal FIFOs");
	goto die;
    }
    if ((rfd = open(s2c, O_RDONLY | NONBLOCK_FLAG)) < 0) {
	perror("Opening server-to-client FIFO");
	goto die;
    }
    if ((server_fifo = open(connect_file, O_WRONLY | NONBLOCK_FLAG)) < 0) {
	perror("Opening server FIFO");
	goto die;
    }
    sprintf(connect, "\n%s %s\n", c2s, s2c);
    write(server_fifo, connect, strlen(connect));
    close(server_fifo);

    if ((wfd = open(c2s, O_WRONLY)) < 0) {
	perror("Opening client-to-server FIFO");
	goto die;
    }
    remove(c2s);
    remove(s2c);

    fprintf(stderr, "[Connected to server]\n");

    if (!set_non_blocking(0) || !set_non_blocking(rfd)) {
	perror("Setting connection non-blocking");
	exit(1);
    }
    while (1) {
	char buffer[1024];
	int count, did_some = 0;

	count = read(0, buffer, sizeof(buffer));
	if (count > 0) {
	    did_some = 1;
	    write_all(wfd, buffer, count);
	}
	count = read(rfd, buffer, sizeof(buffer));
	if (count > 0) {
	    did_some = 1;
	    if (buffer[count - 1] == '\0') {
		write_all(1, buffer, count - 1);
		break;
	    } else
		write_all(1, buffer, count);
	}
	if (!did_some)
	    sleep(1);
    }

    set_blocking(0);
    exit(0);

  die:
    remove(c2s);
    remove(s2c);
    exit(1);

  usage:
    fprintf(stderr, "Usage: %s [-h] [server-connect-file]\n", prog_name);
    exit(1);
}
int pa__init(pa_module*m) {
    struct userdata *u;
    struct stat st;
    pa_sample_spec ss;
    pa_channel_map map;
    pa_modargs *ma;
    struct pollfd *pollfd;
    pa_sink_new_data data;

    pa_assert(m);

    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
        pa_log("Failed to parse module arguments.");
        goto fail;
    }

    ss = m->core->default_sample_spec;
    map = m->core->default_channel_map;
    if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
        pa_log("Invalid sample format specification or channel map");
        goto fail;
    }

    u = pa_xnew0(struct userdata, 1);
    u->core = m->core;
    u->module = m;
    m->userdata = u;
    pa_memchunk_reset(&u->memchunk);
    u->rtpoll = pa_rtpoll_new();
    pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
    u->write_type = 0;

    u->filename = pa_runtime_path(pa_modargs_get_value(ma, "file", DEFAULT_FILE_NAME));

    mkfifo(u->filename, 0666);
    if ((u->fd = open(u->filename, O_RDWR|O_NOCTTY)) < 0) {
        pa_log("open('%s'): %s", u->filename, pa_cstrerror(errno));
        goto fail;
    }

    pa_make_fd_cloexec(u->fd);
    pa_make_fd_nonblock(u->fd);

    if (fstat(u->fd, &st) < 0) {
        pa_log("fstat('%s'): %s", u->filename, pa_cstrerror(errno));
        goto fail;
    }

    if (!S_ISFIFO(st.st_mode)) {
        pa_log("'%s' is not a FIFO.", u->filename);
        goto fail;
    }

    pa_sink_new_data_init(&data);
    data.driver = __FILE__;
    data.module = m;
    pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->filename);
    pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Unix FIFO sink %s", u->filename);
    pa_sink_new_data_set_sample_spec(&data, &ss);
    pa_sink_new_data_set_channel_map(&data, &map);

    if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
        pa_log("Invalid properties");
        pa_sink_new_data_done(&data);
        goto fail;
    }

    u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
    pa_sink_new_data_done(&data);

    if (!u->sink) {
        pa_log("Failed to create sink.");
        goto fail;
    }

    u->sink->parent.process_msg = sink_process_msg;
    u->sink->userdata = u;

    pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
    pa_sink_set_rtpoll(u->sink, u->rtpoll);
    pa_sink_set_max_request(u->sink, pa_pipe_buf(u->fd));
    pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(pa_pipe_buf(u->fd), &u->sink->sample_spec));

    u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
    pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
    pollfd->fd = u->fd;
    pollfd->events = pollfd->revents = 0;

    if (!(u->thread = pa_thread_new(thread_func, u))) {
        pa_log("Failed to create thread.");
        goto fail;
    }

    pa_sink_put(u->sink);

    pa_modargs_free(ma);

    return 0;

fail:
    if (ma)
        pa_modargs_free(ma);

    pa__done(m);

    return -1;
}
Esempio n. 21
0
int pipe_main(int argc, char *argv[])
{
  int filedes[2];
  int ret;

  /* Test FIFO logic */

  printf("\npipe_main: Performing FIFO test\n");
  ret = mkfifo(FIFO_PATH1, 0666);
  if (ret < 0)
    {
      fprintf(stderr, "pipe_main: mkfifo failed with errno=%d\n", errno);
      return 1;
    }

  /* Open one end of the FIFO for reading and the other end for writing.  NOTE:
   * the following might not work on most FIFO implementations because the attempt
   * to open just one end of the FIFO for writing might block.  The NuttX FIFOs block
   * only on open for read-only (see interlock_test()).
   */

  filedes[1] = open(FIFO_PATH1, O_WRONLY);
  if (filedes[1] < 0)
    {
      fprintf(stderr, "pipe_main: Failed to open FIFO %s for writing, errno=%d\n",
              FIFO_PATH1, errno);
      return 2;
    }

  filedes[0] = open(FIFO_PATH1, O_RDONLY);
  if (filedes[0] < 0)
    {
      fprintf(stderr, "pipe_main: Failed to open FIFO %s for reading, errno=%d\n",
              FIFO_PATH1, errno);
      if (close(filedes[1]) != 0)
        {
          fprintf(stderr, "pipe_main: close failed: %d\n", errno);
        }
      return 3;
    }

  /* Then perform the test using those file descriptors */

  ret = transfer_test(filedes[0], filedes[1]);
  if (close(filedes[0]) != 0)
    {
      fprintf(stderr, "pipe_main: close failed: %d\n", errno);
    }
  if (close(filedes[1]) != 0)
    {
      fprintf(stderr, "pipe_main: close failed: %d\n", errno);
    }
  /* unlink(FIFO_PATH1); fails */

  if (ret != 0)
    {
      fprintf(stderr, "pipe_main: FIFO test FAILED (%d)\n", ret);
      return 4;
    }
  printf("pipe_main: FIFO test PASSED\n");

  /* Test PIPE logic */

  printf("\npipe_main: Performing pipe test\n");
  ret = pipe(filedes);
  if (ret < 0)
    {
      fprintf(stderr, "pipe_main: pipe failed with errno=%d\n", errno);
      return 5;
    }

  /* Then perform the test using those file descriptors */

  ret = transfer_test(filedes[0], filedes[1]);
  if (close(filedes[0]) != 0)
    {
      fprintf(stderr, "pipe_main: close failed: %d\n", errno);
    }
  if (close(filedes[1]) != 0)
    {
      fprintf(stderr, "pipe_main: close failed: %d\n", errno);
    }

  if (ret != 0)
    {
      fprintf(stderr, "pipe_main: PIPE test FAILED (%d)\n", ret);
      return 6;
    }
  printf("pipe_main: PIPE test PASSED\n");

  /* Perform the FIFO interlock test */

  printf("\npipe_main: Performing pipe interlock test\n");
  ret = interlock_test();
  if (ret != 0)
    {
      fprintf(stderr, "pipe_main: FIFO interlock test FAILED (%d)\n", ret);
      return 7;
    }
  printf("pipe_main: PIPE interlock test PASSED\n");

  /* Perform the pipe redirection test */

  printf("\npipe_main: Performing redirection test\n");
  ret = redirection_test();
  if (ret != 0)
    {
      fprintf(stderr, "pipe_main: FIFO redirection test FAILED (%d)\n", ret);
      return 7;
    }
  printf("pipe_main: PIPE redirection test PASSED\n");

  fflush(stdout);
  return 0;
}
Esempio n. 22
0
int main()
{
	char buf[64];
	pid_t cpid;
	int sfd, cfd, fd;
	int rnum;
	char pathname[64];

	// make server fifo 
	if(mkfifo(serverfifo, O_CREAT|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) == -1)
	{
		perror("server mkfifo error");
		//exit(-1);
	}else{
		printf("create server fifo successfully.\n");
	}

	// open server fifo and read pid of client, pathname from it
	if((sfd = open(serverfifo, O_RDONLY)) == -1)
	{
		perror("server open server fifo error");
		exit(-1);
	}else{
		printf("open server fifo in readonly mode successfully.\n");
	}

	if((rnum = read(sfd, buf, sizeof(buf))) == -1)
	{
		perror("server read server fifo error");
		exit(-1);
	}else{
		printf("server: read:%s\n", buf);
	}

	sscanf(buf, "%d %s", &cpid, pathname);
	printf("server: get client pid: %d,pathname:%s\n", cpid, pathname);
	// close server fifo
	close(sfd);

	// open client fifo: writeonly
	snprintf(buf, sizeof(buf), "/tmp/client.%d.fifo", cpid);
	printf("server:client fifo is %s\n", buf);
	if((cfd = open(buf, O_WRONLY)) == -1)
	{
		perror("server:open client fifo error");
		exit(-1);
	}else{
		printf("open client fifo for writeonly\n");
	}

	// open file:pathname, read it, and write its content to client fifo
	if((fd = open(pathname, O_RDONLY)) == -1)
	{
		perror("open pathname error.");
		exit(-1);
	}else{
		printf("open pathname successfully.\n");
	}

	while((rnum = read(fd, buf, sizeof(buf))) > 0)
	{
		write(cfd, buf, rnum);
	}

	// close client fifo, pathname
	close(fd);
	close(cfd);

	// delete server fifo
	unlink(serverfifo);

	return 0;
}
Esempio n. 23
0
int main(int argc, char * const *argv)
{
	const char *infile = argv[1];
	const char *outfile = argv[2];
	int fd_in, fd_out;
	int opt;
	float rate = 0.0;
	bool exit_on_end = false;

	while ((opt = getopt(argc, argv, "r:e")) != -1) {
		switch (opt) {
		case 'r':
			rate = atof(optarg);
			break;
		case 'e':
			exit_on_end = true;
			break;
		}
	}

again:
	fd_in = open(infile, O_RDONLY);
	if (fd_in == -1) {
		perror(infile);
		exit(1);
	}

	unlink(outfile);
	if (mkfifo(outfile, 0644) != 0) {
		perror(outfile);
		exit(1);
	}

	signal(SIGPIPE,	SIG_IGN);

	printf("Waiting for connection ...\n");
	fd_out = open(outfile, O_WRONLY);
	if (fd_out == -1) {
		perror(outfile);
		exit(1);
	}

	printf("Streaming ...\n");
	while (1) {
		char buf[1024];
		ssize_t n = read(fd_in, buf, sizeof(buf));
		if (n <= 0) {
			if (exit_on_end) break;
			usleep(1000);
			continue;
		}
		if (write(fd_out, buf, n) == -1) {
			close(fd_out);
			close(fd_in);
			goto again;
		}
		if (rate != 0.0) {
			usleep(1.0e6/rate);
		}
	}

	printf("done\n");
	
	return 0;
}
Esempio n. 24
0
int main(int argc,char *argv[])
{
    //sharepid
    //save what? user's name! 
    //way 1: put it in a char[20], share a 20*512 space;
    //way 2: put it in longlong, then transfer it to char(use ascii)
    //e.g. abcd --> 'a' + [0,1,2,3,4] --> 05 'a' 01 02 03 04. only save half memory
    //improve: use '0' -- asc 48 as basic char, only need (num c0 c1 c2...)
    //I can use address!
    //but think about it: why share memory is invented? 'cause we needn't save it twice
    int userspace = shmget(IPC_PRIVATE,USRLEN*3,0666);
    char *temp = (char *)shmat(userspace,NULL,0);
    memset(temp,0,USRLEN*3);
    //commoninit
    mkfifo(LOGFILE,0666);
    mkfifo(PUBLIC,0666);
    int login=open(LOGFILE,O_RDONLY);
    char buf[1024];

    int brunch=fork();
    if(brunch==0)//listen login, and save the user name in shm
    {
        //one brunch loop here
        char lgname[USRLEN];
        printf("1.1 start listening\n");
        while(memset(lgname,0,USRLEN),read(login,lgname,USRLEN-1)!=0){
            int iflogin=strcmp(lgname,"");  
            if(iflogin)
            {
                //visit the share and add an element
                int *count = (int *)shmat(userspace,NULL,0);
                (*count)++;
                //if I share an address, when I fork, two copy will be Created
                //is it right to change the value by use the pointer?
                char *thisuser=(char *)(shmat(userspace,NULL,0)+*count*USRLEN);
                strncpy(thisuser,lgname,USRLEN);
                printf("1.2 some body login! %s\n",thisuser);

                //beter to open it in child, and write share memory.so problem:
                //if write too fast, we must add some lock to wait all finish reading
            }
        }
    }else{
        //one for write to the users in shm, one for read from PUBLIC
        //keepwrite();
        printf("2.1 for transfer success\n");
        int pubpipe = open(PUBLIC,O_RDONLY);
        printf("2.2 pipe open suc\n");
        int i;
        int fp[512]={0};
        while(1){
            int *count = (int *)shmat(userspace,NULL,0);
            for(i=1;i<=*count;i++)
            {
                char *p = (char *)(shmat(userspace,NULL,0)+i*USRLEN);
                printf("now user: %s %p\n",p,p);
                fp[i]=open(p,O_WRONLY);
            }
            memset(buf,0,1024);
            read(pubpipe,buf,1024);
            printf("%s",buf);
            if(strcmp(buf,"")==0)
            continue;
            if(strstr(buf,":")==NULL)//logoff operation
            {
                for(i = 1;i<=*count;i++)
                {
                    char *p = (char *)shmat(userspace,NULL,0)+i*USRLEN;
                    printf("now user: %s %p\n",p,p);
                    if(strcmp(buf,p)==0){
                        write(fp[i],"EOF\0",4);
                        memset(p,0,USRLEN);
                        (*count)--;
                        printf("%s is offline\n",buf);
                        //now move element ,make sure no empty
                        int j;
                        break;
                    }
                }
                for(i;i<=*count;i++)
                {                  
                    char *p = (char *)shmat(userspace,NULL,0)+i*USRLEN;
                    if(strcmp(p,"")==0){
                        strcpy(p,p+USRLEN);
                        memset(p+USRLEN,0,USRLEN);
                    }
                }
                continue;
            }
            printf("count = %d\n",*count);
            for(i=1;i<=*count;i++)
            {
                char *p = (char *)shmat(userspace,NULL,0)+i*USRLEN;
                write(fp[i],buf,1024);
                close(fp[i]);
            }
        }
    }
}
Esempio n. 25
0
int main()
{
    int server_fifo_fd;
    int client_fifo_fd;

    int res;
    char client_fifo_name[NAME_SIZE];

	MessageClient MC1;
	memset(&MC1, 0 , sizeof(MC1));

//    if(UTIL_CheckFile(SERVER_FIFO_NAME))
	{
		UTIL_DeleteFile(SERVER_FIFO_NAME);
		cout <<"Delete "<< SERVER_FIFO_NAME << endl;
	
	}

    if (mkfifo(SERVER_FIFO_NAME, 0777) == -1)
    {
        fprintf(stderr, "Sorry, create server fifo failure!\n");
        exit(EXIT_FAILURE);
    }

    server_fifo_fd = open(SERVER_FIFO_NAME, O_RDONLY);
    if (server_fifo_fd == -1)
    {
        fprintf(stderr, "Sorry, server fifo open failure!\n");
        exit(EXIT_FAILURE);
    }

//    sleep(5);

//   while ((res = read(server_fifo_fd, &CI, sizeof(CI))) > 0)
   int count =0;
   
   while (1)
   {
	//First read Operation Type
    	if((res = read(server_fifo_fd, &MC1, sizeof(MC1))) > 0)
	{
		
		//CI.str="YYY";

		ResultInfo RI;
		RI.result = SUCCEED;

		RI.MC.client_pid = MC1.client_pid;
		CourseInfo CI;
		LimitInfo LI;
		int OT = MC1.OT;

		switch(OT)
		{
			case Book:
				{
					if((res = read( server_fifo_fd, &CI, sizeof(CI))) > 0)
					{
						//sleep(4);//stand for do some post and get and annylyse

						//do the book thing
						string strHash ;
						strHash.assign(CI.Hash, strlen(CI.Hash));
						Vhash1.push_back(strHash);

						//sleep(4);//stand for do some post and get and analyse

						cout << "Got a book  :" << CI.Hash <<" " << MC1.client_pid << endl;
					}
				}
				break;
			
			case LimitSpeed:
				{

					if((res = read(server_fifo_fd, &LI, sizeof(LI))) > 0)
					{
						//do the Limit thing
						//sleep(4);//stand for do some post and get and annylyse

						cout << "LI.DownloadSpeedLimitTo :" << LI.DownloadSpeedLimitTo << endl;
					}
				}
				break;

			case Status:
				{
				//Vhash3.push_back(strHash);
				//cout << "Vhash3 size " << Vhash3.size() << endl;
				}
				break;
			default:
				break;
		}
		cout << count++ << endl;
		
		sprintf(client_fifo_name, CLIENT_FIFO_NAME, MC1.client_pid);
		client_fifo_fd = open(client_fifo_name, O_WRONLY);
		if (client_fifo_fd == -1)
		{
			fprintf(stderr, "Sorry, client fifo open failure!\n");
			exit(EXIT_FAILURE);
		}
		write(client_fifo_fd, &RI, sizeof(RI));
		close(client_fifo_fd);
	}
	else//keep try open
	{
		sleep(1);//need to sleep for a few second for it will make 100%cpu
	}
    }

    close(server_fifo_fd);
    unlink(SERVER_FIFO_NAME);
    exit(EXIT_SUCCESS);
}
Esempio n. 26
0
/* create_fifo()
 * Creates a new fifo with the given name and permission.
 */
static int create_fifo(char *name, int perm)
{
  if ((mkfifo(name, perm) < 0) && (errno != EEXIST))
    return -1;
  return 0;
}
Esempio n. 27
0
int 
usnet_init_shmmq(usn_shmmq_t *mq, char* fifo_path, 
      int32_t wait_sec, int32_t wait_usec, 
      int32_t shm_key, int32_t shm_size, int32_t sync)
{
   int ret = 0;
   int val;
   char *mem_addr = NULL;
   int mode = 0666 | O_NONBLOCK | O_NDELAY;

   if ( mq == NULL )  {
      //ERROR("null pointer, addr=%p",  mq); 
      return -1;
   }

	errno = 0;
   if ((mkfifo(fifo_path, mode)) < 0)
		if (errno != EEXIST) {
         //ERROR("failed to make fifo, file=%s",  fifo_path); 
			ret = -1;
         goto done;
      }

   if ((mq->_fd = open(fifo_path, O_RDWR)) < 0) {
		ret = -2;
      //ERROR("failed to open fifo, file=%s",  fifo_path); 
      goto done;
   }

	if (mq->_fd > 1024)
	{
		close(mq->_fd);
		ret = -3;
      //ERROR("fd is too small, fd=%d", mq->_fd); 
      goto done;
	}
    
	val = fcntl(mq->_fd, F_GETFL, 0);
	
	if (val == -1) {
		ret = errno ? -errno : val;
      //ERROR("failed to get fl, fd=%d", mq->_fd); 
      goto done;
   }

	if (val & O_NONBLOCK) {
		ret = 0;
      goto done;
   }
	
	ret = fcntl(mq->_fd, F_SETFL, val | O_NONBLOCK | O_NDELAY);

	if (ret < 0) {
      ret = errno ? -errno : ret;
      //ERROR("failed to set fl, fd=%d, ret", mq->_fd, ret); 
      goto done;
   } else
      ret = 0;

	assert(shm_size > C_HEAD_SIZE);

	mq->_shm = usnet_shm_create(shm_key, shm_size);

   if ( mq->_shm == NULL ) {
      mq->_shm = usnet_shm_open(shm_key, shm_size);
      if ( mq->_shm == NULL ) {
		   ret = -1;
         //ERROR("failed to open shm, key=%d, size=%d", shm_key, shm_size);
         goto done;
   	}
      mem_addr = mq->_shm->addr;
      goto setup;
	} else
      mem_addr = mq->_shm->addr;

   // init head portion of shared meme.
   memset(mem_addr, 0, C_HEAD_SIZE * 2 + sizeof(*mq->_adaptive_ctrl));

   // init adaptive control.
   mq->_adaptive_ctrl = (usn_adapctl_t *)mem_addr;
   mq->_adaptive_ctrl->m_uiCheckTimeSpan = 1;
   mq->_adaptive_ctrl->m_uiMsgCount = 0;
   mq->_adaptive_ctrl->m_uiLastCheckTime = time(NULL);
   mq->_adaptive_ctrl->m_uiLastFactor = 1;
   mq->_adaptive_ctrl->m_uiFactor = 1;
   mq->_adaptive_ctrl->m_uiSync = sync;

	mq->_wait_sec = wait_sec;
	mq->_wait_usec = wait_usec;
 
setup:
   mq->_adaptive_ctrl = (usn_adapctl_t *)mem_addr;
   mem_addr += sizeof(*mq->_adaptive_ctrl);
   mq->_enqueued_msg_cnt = (uint32_t*)mem_addr;
   mq->_dequeued_msg_cnt = (uint32_t*)mem_addr + 1;

   //	set head and tail
	mq->_head = (uint32_t*)mem_addr + 2;
	mq->_tail = mq->_head+1;
	mq->_block = (char*) (mq->_tail+1);
	mq->_block_size = shm_size - ( C_HEAD_SIZE * 2 + sizeof(*mq->_adaptive_ctrl) );

	ret = 0;
done:
   return ret;
}
int
sample_event()
{
    struct event evfifo;
#ifdef WIN32
    HANDLE socket;
    /* Open a file. */
    socket = CreateFileA("test.txt",	/* open File */
                         GENERIC_READ | GENERIC_WRITE,		/* open for reading */
                         FILE_SHARE_READ,			/* do not share */
                         NULL,			/* no security */
                         OPEN_ALWAYS,		/* existing file only */
                         FILE_ATTRIBUTE_NORMAL,	/* normal file */
                         NULL);			/* no attr. template */


    if (socket == INVALID_HANDLE_VALUE)
        return 1;

#else
    struct stat st;
    const char *fifo = "event.fifo";
    int socket;

    if (lstat(fifo, &st) == 0) {
        if ((st.st_mode & S_IFMT) == S_IFREG) {
            errno = EEXIST;
            perror("lstat");
            exit(1);
        }
    }

    unlink(fifo);
    if (mkfifo(fifo, 0600) == -1) {
        perror("mkfifo");
        exit(1);
    }

    /* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
#ifdef __linux
    socket = open(fifo, O_RDWR | O_NONBLOCK, 0);
#else
    socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
#endif

    if (socket == -1) {
        perror("open");
        exit(1);
    }

    fprintf(stderr, "Write data to %s\n", fifo);
#endif
    /* Initalize the event library */
    event_init();

    /* Initalize one event */
#ifdef WIN32
    event_set(&evfifo, (evutil_socket_t)socket, EV_READ, fifo_read, &evfifo);
#else
    event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
#endif

    /* Add it to the active events, without a timeout */
    event_add(&evfifo, NULL);

    event_dispatch();
#ifdef WIN32
    CloseHandle(socket);
#endif
    return (0);
}
Esempio n. 29
0
void *carAssistant(void *car){
	
	//Variable which will be used to store the time
	clock_t t;
	
	//Stores the car's information in new variables for easier handling
	struct carAssistInfo *info = (struct carInfo *) car;
	int idCar = info->idCar;
	int parkingTime = info->parkingTime;
	
	int messagelen;
	char message[100];
	
	//Creates a new fifo for the car using the car's unique ID
	char * fifoCar = malloc (sizeof (char));
	sprintf(fifoCar, "car%d", idCar);
	mkfifo(fifoCar,FIFO_PERMISSIONS);	

	//Opens the car's fifo for writing
	int fdA = open(fifoCar, O_WRONLY);
	
	//Locks the access to a critical section
	pthread_mutex_lock(&nLugaresLock); 
	
	//If the park is not full
	if(n_lugares> 0)
	{
		//If there is only one spot left the car enters and the park is now full
		if(n_lugares == 1){
			
			//Registers current time to print in log
			t = clock();
			pthread_mutex_lock(&nLugLock); 
			
			//Registers that there is one more car in the park
			nLug++;
			
			//Prints to log
			printToLog (t, nLug, idCar, "cheio");
			pthread_mutex_unlock(&nLugLock); 
		}else{
			
			//Registers current time to print in log
			t = clock();
			pthread_mutex_lock(&nLugLock); 
			
			//Registers that there is one more car in the park
			nLug++;
			
			//Prints to log
			printToLog (t, nLug, idCar, "estacionamento");
			pthread_mutex_unlock(&nLugLock); 
		}
		
		//Registers that there is one less available spot in the park
		n_lugares--;
		
		sprintf(message,"Entrou!");
		messagelen=strlen(message)+1;
		
		//Transmits to the vehicle tracker thread that the car has entered
		write(fdA,message,messagelen);
		pthread_mutex_unlock(&nLugaresLock);
		
		//The car is parked of the amount that it wants to be
		sleepTicks(parkingTime);

		
		
		pthread_mutex_lock(&nLugaresLock); 
		
		//The car leaves and there is another spot in the park
		n_lugares++; 
		pthread_mutex_unlock(&nLugaresLock);
		pthread_mutex_lock(&nLugLock);
		
		//Registers current time
		t = clock();
		nLug--;
		
		//If the park is opened, the car leaves, else prints that it is closed and won't receive any more cars
		if(opened==0){
			printToLog (t, nLug, idCar, "encerrado");
		}else{
			printToLog (t, nLug, idCar, "saida");
		}
		pthread_mutex_unlock(&nLugLock); 
		
		//Writes to the car's fifo that it left
		sprintf(message,"Saiu!");
		write(fdA,message,messagelen);
		close(fdA);
	}
	//If the park is full:
	else
	{
		
		sprintf(message,"Cheio!");
		messagelen=strlen(message)+1;
		write(fdA,message,messagelen);
		pthread_mutex_unlock(&nLugaresLock);
		close(fdA);
	}
}
Esempio n. 30
0
int acl_fifo_listen(const char *path, int permissions, int block_mode)
{
	char   *myname = "acl_fifo_listen";
	char    buf[BUF_LEN], tbuf[256];
	static int open_mode = 0;
	struct stat st;
	int     fd;
	int     count;

	/*
	 * Create a named pipe (fifo). Do whatever we can so we don't run into
	 * trouble when this process is restarted after crash.  Make sure that
	 * we open a fifo and not something else, then change permissions to
	 * what we wanted them to be, because mkfifo() is subject to umask
	 * settings. Instead we could zero the umask temporarily before
	 * creating the FIFO, but that would cost even more system calls.
	 * Figure out if the fifo needs to be opened O_RDWR or O_RDONLY. Some
	 * systems need one, some need the other. If we choose the wrong mode,
	 * the fifo will stay readable, causing the program to go into a loop.
	 */
	if (unlink(path) && acl_last_error() != ENOENT) {
		acl_msg_error("%s: remove %s: %s", myname, path,
			acl_last_strerror(tbuf, sizeof(tbuf)));
		return -1;
	}
	if (mkfifo(path, permissions) < 0) {
		acl_msg_error("%s: create fifo %s: %s", myname, path,
			acl_last_strerror(tbuf, sizeof(tbuf)));
		return -1;
	}
	switch (open_mode) {
	case 0:
		if ((fd = open(path, O_RDWR | O_NONBLOCK, 0)) < 0) {
			acl_msg_error("%s: open %s: %s", myname, path,
				acl_last_strerror(tbuf, sizeof(tbuf)));
			return -1;
		}
		if (acl_readable(fd) == 0) {
			open_mode = O_RDWR | O_NONBLOCK;
			break;
		}

		open_mode = O_RDONLY | O_NONBLOCK;
		if (acl_msg_verbose)
			acl_msg_info("open O_RDWR makes fifo readable"
				" - trying O_RDONLY");
		(void) close(fd);
		if ((fd = open(path, open_mode, 0)) < 0) {
			acl_msg_error("%s: open %s: %s", myname, path,
				acl_last_strerror(tbuf, sizeof(tbuf)));
			return -1;
		}
		break;
	default:
		if ((fd = open(path, open_mode, 0)) < 0) {
			acl_msg_error("%s: open %s: %s", myname, path,
				acl_last_strerror(tbuf, sizeof(tbuf)));
			return -1;
		}
		break;
	}

	/*
	 * Make sure we opened a FIFO and skip any cruft that might have
	 * accumulated before we opened it.
	 */
	if (fstat(fd, &st) < 0) {
		acl_msg_error("%s: fstat %s: %s", myname, path,
			acl_last_strerror(tbuf, sizeof(tbuf)));
		close(fd);
		return -1;
	}
	if (S_ISFIFO(st.st_mode) == 0) {
		acl_msg_error("%s: not a fifo: %s", myname, path);
		close(fd);
		return -1;
	}
	if (fchmod(fd, permissions) < 0) {
		acl_msg_error("%s: fchmod %s: %s", myname, path,
			acl_last_strerror(tbuf, sizeof(tbuf)));
		close(fd);
		return -1;
	}
	acl_non_blocking(fd, block_mode);
	while ((count = acl_peekfd(fd)) > 0 && read(fd, buf,
		BUF_LEN < count ? BUF_LEN : count) > 0) {
	}

	return fd;
}