예제 #1
0
static int
printstatus(int status)
{
	int exited = 0;

	/*
	 * Here is a tricky presentation problem.  This solution
	 * is still not entirely satisfactory but since there
	 * are no wait status constructors it will have to do.
	 */
	if (WIFSTOPPED(status)) {
		int sig = WSTOPSIG(status);
		tprintf("[{WIFSTOPPED(s) && WSTOPSIG(s) == %s%s}",
			signame(sig & 0x7f),
			sig & 0x80 ? " | 0x80" : "");
		status &= ~W_STOPCODE(sig);
	}
	else if (WIFSIGNALED(status)) {
		tprintf("[{WIFSIGNALED(s) && WTERMSIG(s) == %s%s}",
			signame(WTERMSIG(status)),
			WCOREDUMP(status) ? " && WCOREDUMP(s)" : "");
		status &= ~(W_EXITCODE(0, WTERMSIG(status)) | WCOREFLAG);
	}
	else if (WIFEXITED(status)) {
		tprintf("[{WIFEXITED(s) && WEXITSTATUS(s) == %d}",
			WEXITSTATUS(status));
		exited = 1;
		status &= ~W_EXITCODE(WEXITSTATUS(status), 0);
	}
#ifdef WIFCONTINUED
	else if (WIFCONTINUED(status)) {
		tprints("[{WIFCONTINUED(s)}");
		status &= ~W_CONTINUED;
	}
#endif
	else {
		tprintf("[%#x]", status);
		return 0;
	}

	if (status) {
		unsigned int event = (unsigned int) status >> 16;
		if (event) {
			tprints(" | ");
			printxval(ptrace_events, event, "PTRACE_EVENT_???");
			tprints(" << 16");
			status &= 0xffff;
		}
		if (status)
			tprintf(" | %#x", status);
	}
	tprints("]");

	return exited;
}
static int
sigstr_to_uint(const char *s)
{
	if (*s >= '0' && *s <= '9')
		return string_to_uint_upto(s, 255);

	if (strncasecmp(s, "SIG", 3) == 0)
		s += 3;

	for (int i = 0; i <= 255; ++i) {
		const char *name = signame(i);

		if (strncasecmp(name, "SIG", 3) != 0)
			continue;

		name += 3;

		if (strcasecmp(name, s) != 0)
			continue;

		return i;
	}

	return -1;
}
예제 #3
0
파일: main.c 프로젝트: icanhas/yantar
void
Sys_SigHandler(int signal)
{
	static qbool signalcaught = qfalse;
	const char *name;
	
	name = signame(signal);
	fprintf(stderr, "GOOFED: received signal %d (%s)", signal, name);
	if(signalcaught)
		fprintf(stderr,
			"DOUBLE SIGNAL FAULT: received signal %d (%s), exiting...\n",
			signal, name);
	else{
		signalcaught = qtrue;
		vmsetforceunload();
		if(!com_dedicated->integer)
			clshutdown(va("received signal %d (%s)", signal, name), qtrue, qtrue);
		svshutdown(va("received signal %d (%s)", signal, name));
		vmclearforceunload();
	}
	fflush(stdout);
	fflush(stderr);
	if(signal == SIGTERM || signal == SIGINT)
		Sys_Exit(1);
	else
		Sys_Exit(2);
}
예제 #4
0
파일: status.c 프로젝트: codemac/es-shell
/* mkstatus -- turn a unix exit(2) status into a string */
extern char *mkstatus(int status) {
	if (SIFSIGNALED(status)) {
		char *name = signame(STERMSIG(status));
		if (SCOREDUMP(status))
			name = str("%s+core", name);
		return name;
	}
	return str("%d", SEXITSTATUS(status));
}
예제 #5
0
파일: signal.c 프로젝트: GeoffGats/strace
int
sys_kill(struct tcb *tcp)
{
	if (entering(tcp)) {
		tprintf("%ld, %s",
			widen_to_long(tcp->u_arg[0]),
			signame(tcp->u_arg[1])
		);
	}
	return 0;
}
//=============================================================================
//=============================================================================
vector<string> PushThreadShared::get_sig_list_waiting()
{
	omni_mutex_lock sync(*this);
	vector<string>	list;
	for (unsigned int i=0 ; i<events.size() ; i++)
	{
		HdbCmdData *ev = events[i];
		string	signame(ev->ev_data->attr_name);
		list.push_back(signame);
	}
	return list;
}
예제 #7
0
static int
createhash(char *name, struct hashinfo **hinfop)
{
	char *hfile;
	int ofd, cc;
	int count;
	struct hashinfo *hinfo;

	hfile = signame(name);
	ofd = open(hfile, O_RDWR|O_CREAT, 0666);
	if (ofd < 0) {
		perror(hfile);
		free(hfile);
		return -1;
	}

	/*
	 * Hash the image file
	 */
	if (hashimage(name, hinfop)) {
		free(hfile);
		return -1;
	}

	/*
	 * Write the image file
	 */
	hinfo = *hinfop;
	strcpy(hinfo->magic, HASH_MAGIC);
	hinfo->version = HASH_VERSION;
	hinfo->hashtype = hashtype;
	count = sizeof(*hinfo) + hinfo->nregions*sizeof(struct hashregion);
	cc = write(ofd, hinfo, count);
	close(ofd);
	if (cc != count) {
		if (cc < 0)
			perror(hfile);
		else
			fprintf(stderr,
				"%s: incomplete write (%d)\n", hfile, cc);
		free(hfile);
		return -1;
	}

	free(hfile);
	nhregions = hinfo->nregions;
	printf("%s: %lu chunks, %lu regions, %lu hashregions, %qu data bytes\n",
	       name, nchunks, nregions, nhregions, ndatabytes);
#ifdef TIMEIT
	printf("%qu bytes: inflate cycles: %qu\n", ndatabytes, dcycles);
#endif
	return 0;
}
예제 #8
0
/* try to install signal handler and check result */
static void install_sighandler(int signum, void (*handler) (int))
{
  struct sigaction act;
  memset(&act, 0, sizeof(struct sigaction));
  act.sa_handler = handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags = SA_RESTART | SA_NOCLDSTOP;
  if (sigaction(signum, &act, NULL) != 0)
  {
    log_log(LOG_ERR, "error installing signal handler for '%s': %s",
            signame(signum), strerror(errno));
    exit(EXIT_FAILURE);
  }
}
//=============================================================================
vector<string>  PushThreadShared::get_sig_not_on_error_list()
{
	sig_lock->lock();
	vector<string>	list;
	for (unsigned int i=0 ; i<signals.size() ; i++)
	{
		if (signals[i].dbstate==Tango::ON)
		{
			string	signame(signals[i].name);
			list.push_back(signame);
		}
	}
	sig_lock->unlock();
	return list;
}
예제 #10
0
static int
readhashinfo(char *name, struct hashinfo **hinfop)
{
	struct hashinfo hi, *hinfo;
	char *hname;
	int fd, nregbytes, cc;

	hname = signame(name);
	fd = open(hname, O_RDONLY, 0666);
	if (fd < 0) {
		perror(hname);
		free(hname);
		return -1;
	}
	cc = read(fd, &hi, sizeof(hi));
	if (cc != sizeof(hi)) {
	readbad:
		if (cc < 0)
			perror(hname);
		else
			fprintf(stderr, "%s: too short\n", hname);
	bad:
		close(fd);
		free(hname);
		return -1;
	}
	if (strcmp(hi.magic, HASH_MAGIC) != 0 || hi.version != HASH_VERSION) {
		fprintf(stderr, "%s: not a valid signature file\n", hname);
		goto bad;
	}
	nregbytes = hi.nregions * sizeof(struct hashregion);
	hinfo = malloc(sizeof(hi) + nregbytes);
	if (hinfo == 0) {
		fprintf(stderr, "%s: not enough memory for info\n", hname);
		goto bad;
	}
	*hinfo = hi;
	cc = read(fd, hinfo->regions, nregbytes);
	if (cc != nregbytes) {
		free(hinfo);
		goto readbad;
	}

	close(fd);
	free(hname);
	*hinfop = hinfo;
	return 0;
}
예제 #11
0
MPERS_PRINTER_DECL(void, print_sigevent, struct tcb *tcp, const long addr)
{
	struct_sigevent sev;

	if (umove_or_printaddr(tcp, addr, &sev))
		return;

	tprints("{");
	if (sev.sigev_value.sival_ptr) {
		tprintf("sigev_value={int=%d, ptr=",
			sev.sigev_value.sival_int);
		printaddr((unsigned long) sev.sigev_value.sival_ptr);
		tprints("}, ");
	}

	tprints("sigev_signo=");
	switch (sev.sigev_notify) {
	case SIGEV_SIGNAL:
	case SIGEV_THREAD:
	case SIGEV_THREAD_ID:
		tprints(signame(sev.sigev_signo));
		break;
	default:
		tprintf("%u", sev.sigev_signo);
	}

	tprints(", sigev_notify=");
	printxval(sigev_value, sev.sigev_notify, "SIGEV_???");

	switch (sev.sigev_notify) {
	case SIGEV_THREAD_ID:
		tprintf(", sigev_notify_thread_id=%d", sev.sigev_un.tid);
		break;
	case SIGEV_THREAD:
		tprints(", sigev_notify_function=");
		printaddr(sev.sigev_un.sigev_thread.function);
		tprints(", sigev_notify_attributes=");
		printaddr(sev.sigev_un.sigev_thread.attribute);
		break;
	}
	tprints("}");
}
예제 #12
0
파일: main.c 프로젝트: tioui/EiffelStudio
rt_private Signal_t emergency(int sig)
{
	/* A signal has been trapped while we were failing peacefully. The memory
	 * must really be in a desastrous state, so print out a give-up message
	 * and exit.
	 * The code is protected in case `emergency' is triggered while calling `print_err_msg'
	 * which was happening in eweasel test#vsrp208 because we got a SIGPIPE when outputs
	 * of `ec' are redirected and closed while the compiler is not yet done.
	 */
		
	if (!emergency_call_success) {
		emergency_call_success = 1;
		print_err_msg(stderr, "\n\n%s: PANIC: caught signal #%d (%s) -- Giving up...\n",
			egc_system_name, sig, signame(sig));
	}

	exit(2);							/* Really abnormal termination */

	/* NOTREACHED */
}
예제 #13
0
void
printsigevent(struct tcb *tcp, long arg)
{
	struct sigevent sev;

#if SUPPORTED_PERSONALITIES > 1
	if (current_wordsize == 4) {
		printsigevent32(tcp, arg);
		return;
	}
#endif
	if (umove(tcp, arg, &sev) < 0)
		tprints("{...}");
	else {
		tprintf("{%p, ", sev.sigev_value.sival_ptr);
		if (sev.sigev_notify == SIGEV_SIGNAL)
			tprintf("%s, ", signame(sev.sigev_signo));
		else
			tprintf("%u, ", sev.sigev_signo);
		printxval(sigev_value, sev.sigev_notify, "SIGEV_???");
		tprints(", ");
		if (sev.sigev_notify == SIGEV_THREAD_ID)
#if defined(HAVE_STRUCT_SIGEVENT__SIGEV_UN__PAD)
			/* _pad[0] is the _tid field which might not be
			   present in the userlevel definition of the
			   struct.  */
			tprintf("{%d}", sev._sigev_un._pad[0]);
#elif defined(HAVE_STRUCT_SIGEVENT___PAD)
			tprintf("{%d}", sev.__pad[0]);
#else
# warning unfamiliar struct sigevent => incomplete SIGEV_THREAD_ID decoding
			tprints("{...}");
#endif
		else if (sev.sigev_notify == SIGEV_THREAD)
			tprintf("{%p, %p}", sev.sigev_notify_function,
				sev.sigev_notify_attributes);
		else
			tprints("{...}");
		tprints("}");
	}
예제 #14
0
static int
qual_signal(const char *s, const unsigned int bitflag, const int not)
{
	unsigned int i;

	if (*s >= '0' && *s <= '9') {
		int signo = string_to_uint(s);
		if (signo < 0 || signo > 255)
			return -1;
		qualify_one(signo, bitflag, not, -1);
		return 0;
	}
	if (strncasecmp(s, "SIG", 3) == 0)
		s += 3;
	for (i = 0; i <= NSIG; i++) {
		if (strcasecmp(s, signame(i) + 3) == 0) {
			qualify_one(i, bitflag, not, -1);
			return 0;
		}
	}
	return -1;
}
예제 #15
0
static void
printsigevent32(struct tcb *tcp, long arg)
{
	struct {
		int     sigev_value;
		int     sigev_signo;
		int     sigev_notify;

		union {
			int     tid;
			struct {
				int     function, attribute;
			} thread;
		} un;
	} sev;

	if (umove(tcp, arg, &sev) < 0)
		tprints("{...}");
	else {
		tprintf("{%#x, ", sev.sigev_value);
		if (sev.sigev_notify == SIGEV_SIGNAL)
			tprintf("%s, ", signame(sev.sigev_signo));
		else
			tprintf("%u, ", sev.sigev_signo);
		printxval(sigev_value, sev.sigev_notify, "SIGEV_???");
		tprints(", ");
		if (sev.sigev_notify == SIGEV_THREAD_ID)
			tprintf("{%d}", sev.un.tid);
		else if (sev.sigev_notify == SIGEV_THREAD)
			tprintf("{%#x, %#x}",
				sev.un.thread.function,
				sev.un.thread.attribute);
		else
			tprints("{...}");
		tprints("}");
	}
}
예제 #16
0
파일: mgmt.c 프로젝트: markuspeloquin/egg
int
run_processes(const struct proc_spec *specs, uint16_t count)
{
	const int SEMFLAG = IPC_CREAT | IPC_EXCL | 0600;

	union semun	sem_arg;
	struct sembuf	sem_op;
	unsigned short	sem_init[] = { 0, 0 };
	pid_t		*children = 0;
	unsigned	seed;
	int		semid = -1;
	int		status;

	if (!(children = calloc(count, sizeof(pid_t)))) {
		fprintf(stderr, "%s: out of memory\n", prog);
		status = -1;
		goto end;
	}

	/* create semaphore, serves as a barrier */
	if ((semid = semget(IPC_PRIVATE, 1, SEMFLAG)) == -1) {
		fprintf(stderr, "%s: semget failed: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* initialize semaphore values to 0 */
	sem_arg.array = sem_init;
	if (semctl(semid, 0, SETALL, sem_arg) == -1) {
		fprintf(stderr, "%s: semctl(SETVAL) failed: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* all processes need to be seeded seperately, so this gets
	 * incremented in the loop */
	seed = time(0);

	/* start workers */
	for (uint16_t i = 0; i < count; i++) {
		pid_t pid = fork();
		if (pid == -1) {
			fprintf(stderr, "%s: fork failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		} else if (!pid) {
			srand(seed);
			if (worker_begin(specs + i, semid) == -1)
				exit(1);
			exit(0);
		}
		children[i] = pid;
		seed++;
	}

	/* spin until all processes are waiting on the semaphore, or one
	 * process ends prematurely */
	for (;;) {
		pid_t pid;
		int val;

		if ((val = semctl(semid, 0, GETNCNT)) == -1) {
			fprintf(stderr, "%s: semctl(GETNCNT) failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		}
		if (val == count) break; /* ready */

		if ((pid = waitpid(-1, 0, WNOHANG)) == -1) {
			fprintf(stderr, "%s: waitpid failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		} else if (pid) {
			fprintf(stderr, "%s: at least one process exited "
			    "prematurely\n", prog);
			status = -1;
			goto end;
		}

		sched_yield();
	}

	/* release the processes to start*/
	sem_op.sem_num = 0;
	sem_op.sem_op = count;
	sem_op.sem_flg = 0;
	if (semop(semid, &sem_op, 1) == -1) {
		fprintf(stderr, "%s: failed to signal semaphore: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* spin until all processes are waiting on the semaphore, or one
	 * process ends prematurely */
	for (;;) {
		pid_t pid;
		int val;

		if ((val = semctl(semid, 0, GETNCNT)) == -1) {
			fprintf(stderr, "%s: semctl(GETNCNT) failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		}
		if (val == count) break; /* all done working */

		if ((pid = waitpid(-1, 0, WNOHANG)) == -1) {
			fprintf(stderr, "%s: waitpid failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		} else if (pid) {
			fprintf(stderr, "%s: at least one process exited "
			    "prematurely\n", prog);
			status = -1;
			goto end;
		}

		sched_yield();
	}

	/* release the processes to clean up */
	sem_op.sem_num = 0;
	sem_op.sem_op = count;
	sem_op.sem_flg = 0;
	if (semop(semid, &sem_op, 1) == -1) {
		fprintf(stderr, "%s: failed to signal semaphore: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* wait for children to exit */
	for (uint16_t running = count; running;) {
		int		child_status = 0;
		pid_t		pid;
		uint16_t	id;

		if ((pid = waitpid(-1, &child_status, 0)) == -1) {
			assert(errno == EINTR);
			continue;
		}

		for (id = 0; id < count; id++)
			if (children[id] == pid) break;
		assert(id != count);

		children[id] = 0;
		running--;

		if (WIFEXITED(child_status)) {
			if (WEXITSTATUS(child_status)) {
				fprintf(stderr,
				    "%s: process %hu exited with %d\n",
				    prog, id, WEXITSTATUS(child_status));
				status = -1;
				goto end;
			}
		} else {
			int signum = WTERMSIG(child_status);
			fprintf(stderr,
			    "%s: process %hu terminated with %s (%d)\n",
			    prog, id, signame(signum), signum);
			status = -1;
			goto end;
		}
	}

	status = 0;
end:
	if (children) {
		for (uint16_t i = 0; i < count; i++)
			if (children[i])
				/* this line reads quite well */
				kill(children[i], SIGKILL);
		/* if the children have all been killed, I don't know what
		 * good it does to free them */
		free(children);
	}
	if (semid != -1) {
		if (semctl(semid, 0, IPC_RMID) == -1) {
			fprintf(stderr,
			    "%s: semctl(IPC_RMID) failed: %s\n",
			    prog, strerror(errno));
			status = -1;
		}
	}
	return status;
}
예제 #17
0
/* the main program... */
int main(int argc, char *argv[])
{
  int i;
  sigset_t signalmask, oldmask;
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
  struct timespec ts;
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
  /* close all file descriptors (except stdin/out/err) */
  i = sysconf(_SC_OPEN_MAX) - 1;
  /* if the system does not have OPEN_MAX just close the first 32 and
     hope we closed enough */
  if (i < 0)
    i = 32;
  for (; i > 3; i--)
    close(i);
  /* parse the command line */
  parse_cmdline(argc, argv);
  /* clean the environment */
#ifdef HAVE_CLEARENV
  if (clearenv() || putenv("HOME=/") || putenv("TMPDIR=/tmp") ||
      putenv("LDAPNOINIT=1"))
  {
    log_log(LOG_ERR, "clearing environment failed");
    exit(EXIT_FAILURE);
  }
#else /* not HAVE_CLEARENV */
  /* this is a bit ugly */
  environ = sane_environment;
#endif /* not HAVE_CLEARENV */
  /* disable the nss_ldap module for this process */
  disable_nss_ldap();
  /* set LDAP log level */
  if (myldap_set_debuglevel(nslcd_debugging) != LDAP_SUCCESS)
    exit(EXIT_FAILURE);
  /* read configuration file */
  cfg_init(NSLCD_CONF_PATH);
  /* set default mode for pidfile and socket */
  (void)umask((mode_t)0022);
  /* see if someone already locked the pidfile
     if --check option was given exit TRUE if daemon runs
     (pidfile locked), FALSE otherwise */
  if (nslcd_checkonly)
  {
    if (is_locked(NSLCD_PIDFILE))
    {
      log_log(LOG_DEBUG, "pidfile (%s) is locked", NSLCD_PIDFILE);
      exit(EXIT_SUCCESS);
    }
    else
    {
      log_log(LOG_DEBUG, "pidfile (%s) is not locked", NSLCD_PIDFILE);
      exit(EXIT_FAILURE);
    }
  }
  /* normal check for pidfile locked */
  if (is_locked(NSLCD_PIDFILE))
  {
    log_log(LOG_ERR, "daemon may already be active, cannot acquire lock (%s): %s",
            NSLCD_PIDFILE, strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* daemonize */
  if ((!nslcd_debugging) && (!nslcd_nofork) && (daemon(0, 0) < 0))
  {
    log_log(LOG_ERR, "unable to daemonize: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* intilialize logging */
  if (!nslcd_debugging)
    log_startlogging();
  log_log(LOG_INFO, "version %s starting", VERSION);
  /* start subprocess to do invalidating if reconnect_invalidate is set */
  for (i = 0; i < LM_NONE; i++)
    if (nslcd_cfg->reconnect_invalidate[i])
      break;
  if (i < LM_NONE)
    invalidator_start();
  /* write pidfile */
  create_pidfile(NSLCD_PIDFILE);
  /* install handler to close stuff off on exit and log notice */
  if (atexit(exithandler))
  {
    log_log(LOG_ERR, "atexit() failed: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* create socket */
  nslcd_serversocket = create_socket(NSLCD_SOCKET);
  if ((nslcd_cfg->gid != NOGID) && (nslcd_cfg->uidname != NULL))
  {
#ifdef HAVE_INITGROUPS
    /* load supplementary groups */
    if (initgroups(nslcd_cfg->uidname, nslcd_cfg->gid) < 0)
      log_log(LOG_WARNING, "cannot initgroups(\"%s\",%d) (ignored): %s",
              nslcd_cfg->uidname, (int)nslcd_cfg->gid, strerror(errno));
    else
      log_log(LOG_DEBUG, "initgroups(\"%s\",%d) done",
              nslcd_cfg->uidname, (int)nslcd_cfg->gid);
#else /* not HAVE_INITGROUPS */
#ifdef HAVE_SETGROUPS
    /* just drop all supplemental groups */
    if (setgroups(0, NULL) < 0)
      log_log(LOG_WARNING, "cannot setgroups(0,NULL) (ignored): %s",
              strerror(errno));
    else
      log_log(LOG_DEBUG, "setgroups(0,NULL) done");
#else /* not HAVE_SETGROUPS */
    log_log(LOG_DEBUG, "neither initgroups() or setgroups() available");
#endif /* not HAVE_SETGROUPS */
#endif /* not HAVE_INITGROUPS */
  }
  /* change to nslcd gid */
  if (nslcd_cfg->gid != NOGID)
  {
    if (setgid(nslcd_cfg->gid) != 0)
    {
      log_log(LOG_ERR, "cannot setgid(%d): %s",
              (int)nslcd_cfg->gid, strerror(errno));
      exit(EXIT_FAILURE);
    }
    log_log(LOG_DEBUG, "setgid(%d) done", (int)nslcd_cfg->gid);
  }
  /* change to nslcd uid */
  if (nslcd_cfg->uid != NOUID)
  {
    if (setuid(nslcd_cfg->uid) != 0)
    {
      log_log(LOG_ERR, "cannot setuid(%d): %s",
              (int)nslcd_cfg->uid, strerror(errno));
      exit(EXIT_FAILURE);
    }
    log_log(LOG_DEBUG, "setuid(%d) done", (int)nslcd_cfg->uid);
  }
  /* block all these signals so our worker threads won't handle them */
  sigemptyset(&signalmask);
  sigaddset(&signalmask, SIGHUP);
  sigaddset(&signalmask, SIGINT);
  sigaddset(&signalmask, SIGQUIT);
  sigaddset(&signalmask, SIGABRT);
  sigaddset(&signalmask, SIGPIPE);
  sigaddset(&signalmask, SIGTERM);
  sigaddset(&signalmask, SIGUSR1);
  sigaddset(&signalmask, SIGUSR2);
  pthread_sigmask(SIG_BLOCK, &signalmask, &oldmask);
  /* start worker threads */
  log_log(LOG_INFO, "accepting connections");
  nslcd_threads = (pthread_t *)malloc(nslcd_cfg->threads * sizeof(pthread_t));
  if (nslcd_threads == NULL)
  {
    log_log(LOG_CRIT, "main(): malloc() failed to allocate memory");
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nslcd_cfg->threads; i++)
  {
    if (pthread_create(&nslcd_threads[i], NULL, worker, NULL))
    {
      log_log(LOG_ERR, "unable to start worker thread %d: %s",
              i, strerror(errno));
      exit(EXIT_FAILURE);
    }
  }
  pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
  /* install signalhandlers for some signals */
  install_sighandler(SIGHUP, sig_handler);
  install_sighandler(SIGINT, sig_handler);
  install_sighandler(SIGQUIT, sig_handler);
  install_sighandler(SIGABRT, sig_handler);
  install_sighandler(SIGPIPE, SIG_IGN);
  install_sighandler(SIGTERM, sig_handler);
  install_sighandler(SIGUSR1, sig_handler);
  install_sighandler(SIGUSR2, SIG_IGN);
  /* wait until we received a signal */
  while ((nslcd_receivedsignal == 0) || (nslcd_receivedsignal == SIGUSR1))
  {
    sleep(INT_MAX); /* sleep as long as we can or until we receive a signal */
    if (nslcd_receivedsignal == SIGUSR1)
    {
      log_log(LOG_INFO, "caught signal %s (%d), refresh retries",
              signame(nslcd_receivedsignal), nslcd_receivedsignal);
      myldap_immediate_reconnect();
      nslcd_receivedsignal = 0;
    }
  }
  /* print something about received signal */
  log_log(LOG_INFO, "caught signal %s (%d), shutting down",
          signame(nslcd_receivedsignal), nslcd_receivedsignal);
  /* cancel all running threads */
  for (i = 0; i < nslcd_cfg->threads; i++)
    if (pthread_cancel(nslcd_threads[i]))
      log_log(LOG_WARNING, "failed to stop thread %d (ignored): %s",
              i, strerror(errno));
  /* close server socket to trigger failures in threads waiting on accept() */
  close(nslcd_serversocket);
  nslcd_serversocket = -1;
  /* if we can, wait a few seconds for the threads to finish */
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
  ts.tv_sec = time(NULL) + 3;
  ts.tv_nsec = 0;
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
  for (i = 0; i < nslcd_cfg->threads; i++)
  {
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
    pthread_timedjoin_np(nslcd_threads[i], NULL, &ts);
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
    if (pthread_kill(nslcd_threads[i], 0) == 0)
      log_log(LOG_ERR, "thread %d is still running, shutting down anyway", i);
  }
  /* we're done */
  return EXIT_FAILURE;
}
예제 #18
0
static int
measured_exec(const char *device, char *const *args)
{
	struct disk_stats	stats0;
	struct disk_stats	stats1;
	char			stat_path[PATH_MAX];
	uint64_t		time0;
	uint64_t		time1;
	uint32_t		bytes;
	uint32_t		milli_io;
	float			milli_tot;
	float			seconds;
	int			status;
	pid_t			pid;
	uint16_t		sector_sz;

	if (find_device_stat(device, stat_path) == -1)
		return -1;

	if ((sector_sz = sector_size(device)) == -1) {
		fprintf(stderr, "%s: failed to determine sector size: %s\n",
		    prog, strerror(errno));
		return -1;
	}

	if (drop_cache() == -1)
		return -1;

	/* collect opening data */
	if (read_disk_stats(prog, stat_path, &stats0) == -1)
		return -1;
	time0 = clock_monotonic();

	/* start child */
	if ((pid = fork()) == -1) {
	fprintf(stderr, "%s: fork failed: %s\n",
		    prog, strerror(errno));
		return -1;
	} else if (!pid) {
		execvp(*args, args);
		fprintf(stderr, "%s: exec failed: %s\n",
		    prog, strerror(errno));
		exit(0xff);
	}

	/* wait for child */
	status = 0;
	for (;;) {
		if (waitpid(pid, &status, 0) == -1) {
			if (errno == EINTR) continue;
			fprintf(stderr, "%s: wait failed: %s\n",
			    prog, strerror(errno));
			return -1;
		}
		break;
	}

	/* collect closing data */
	if (read_disk_stats(prog, stat_path, &stats1) == -1)
		return -1;
	time1 = clock_monotonic();

	/* check for child error */
	if (WIFSIGNALED(status)) {
		fprintf(stderr, "%s: child terminated by signal %s\n",
		    prog, signame(WTERMSIG(status)));
		return -1;
	} else if (WEXITSTATUS(status)) {
		if (WEXITSTATUS(status) != 0xff)
			fprintf(stderr, "%s: child exited with %d\n",
			    prog, WEXITSTATUS(status));
		return -1;
	}

	/* process data */
	bytes = ((stats1.sectors_read + stats1.sectors_written) -
	    (stats0.sectors_read + stats0.sectors_written)) * sector_sz;

	milli_io = stats1.milli_io - stats0.milli_io;
	milli_tot = (time1 - time0) / 1000000.0f;
	seconds = (time1 - time0) / 1000000000.0f;

	/* print data */
	printf("RATE_KBPS\t%.10e\n", bytes / (seconds * 1024));
	printf("RATE_MBPS\t%.10e\n", bytes / (seconds * 1048576));
	printf("TIME_S\t\t%.10e\n", seconds);
	printf("UTIL\t\t%.10e\n", milli_io / milli_tot);

	return 0;
}
예제 #19
0
static void
ktrsyscall(struct ktr_syscall *ktr)
{
	int narg = ktr->ktr_narg;
	register_t *ip;

	if (ktr->ktr_code >= nsyscalls || ktr->ktr_code < 0)
		(void)printf("[%d]", ktr->ktr_code);
	else
		(void)printf("%s", syscallnames[ktr->ktr_code]);
	ip = &ktr->ktr_args[0];
	if (narg) {
		char c = '(';
		if (fancy) {

#define print_number(i,n,c) do {                      \
	if (decimal)                                  \
		(void)printf("%c%ld", c, (long)*i);   \
	else                                          \
		(void)printf("%c%#lx", c, (long)*i);  \
	i++;                                          \
	n--;                                          \
	c = ',';                                      \
	} while (0);

			if (ktr->ktr_code == SYS_ioctl) {
				const char *cp;
				print_number(ip,narg,c);
				if ((cp = ioctlname(*ip)) != NULL)
					(void)printf(",%s", cp);
				else {
					if (decimal)
						(void)printf(",%ld", (long)*ip);
					else
						(void)printf(",%#lx ", (long)*ip);
				}
				c = ',';
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_access) {
				print_number(ip,narg,c);
				(void)putchar(',');
				accessmodename ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_open ||
				   ktr->ktr_code == SYS_mq_open) {
				int	flags;
				int	mode;
				print_number(ip,narg,c);
				flags = *ip;
				mode = *++ip;
				(void)putchar(',');
				flagsandmodename (flags, mode, decimal);
				ip++;
				narg-=2;
			} else if (ktr->ktr_code == SYS_wait4) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				wait4optname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_chmod ||
				   ktr->ktr_code == SYS_fchmod ||
				   ktr->ktr_code == SYS_lchmod) {
				print_number(ip,narg,c);
				(void)putchar(',');
				modename ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_mknod) {
				print_number(ip,narg,c);
				(void)putchar(',');
				modename ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_getfsstat) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				getfsstatflagsname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_mount) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				mountflagsname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_unmount) {
				print_number(ip,narg,c);
				(void)putchar(',');
				mountflagsname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_recvmsg ||
				   ktr->ktr_code == SYS_sendmsg) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				sendrecvflagsname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_recvfrom ||
				   ktr->ktr_code == SYS_sendto) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				sendrecvflagsname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_chflags ||
				   ktr->ktr_code == SYS_fchflags) {
				print_number(ip,narg,c);
				(void)putchar(',');
				modename((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_kill) {
				print_number(ip,narg,c);
				(void)putchar(',');
				signame((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_reboot) {
				(void)putchar('(');
				rebootoptname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_umask) {
				(void)putchar('(');
				modename((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_msync) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				msyncflagsname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_mmap) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				mmapprotname ((int)*ip);
				(void)putchar(',');
				ip++;
				narg--;
				mmapflagsname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_mprotect) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				mmapprotname ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_madvise) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				madvisebehavname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_setpriority) {
				(void)putchar('(');
				prioname((int)*ip);
				ip++;
				narg--;
				c = ',';
				print_number(ip,narg,c);
				print_number(ip,narg,c);
			} else if (ktr->ktr_code == SYS_fcntl) {
				int cmd;
				int arg;
				print_number(ip,narg,c);
				cmd = *ip;
				arg = *++ip;
				(void)putchar(',');
				fcntlcmdname(cmd, arg, decimal);
				ip++;
				narg-=2;
			} else if (ktr->ktr_code == SYS_socket) {
				(void)putchar('(');
				sockdomainname((int)*ip);
				ip++;
				narg--;
				(void)putchar(',');
				socktypename((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_setsockopt ||
				   ktr->ktr_code == SYS_getsockopt) {
				print_number(ip,narg,c);
				(void)putchar(',');
				sockoptlevelname((int)*ip, decimal);
				ip++;
				narg--;
				(void)putchar(',');
				sockoptname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_lseek) {
				print_number(ip,narg,c);
				/* Hidden 'pad' argument, not in lseek(2) */
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				(void)putchar(',');
				whencename ((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_flock) {
				print_number(ip,narg,c);
				(void)putchar(',');
				flockname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_mkfifo ||
				   ktr->ktr_code == SYS_mkdir) {
				print_number(ip,narg,c);
				(void)putchar(',');
				modename((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_shutdown) {
				print_number(ip,narg,c);
				(void)putchar(',');
				shutdownhowname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_socketpair) {
				(void)putchar('(');
				sockdomainname((int)*ip);
				ip++;
				narg--;
				(void)putchar(',');
				socktypename((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_getrlimit ||
				   ktr->ktr_code == SYS_setrlimit) {
				(void)putchar('(');
				rlimitname((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_quotactl) {
				print_number(ip,narg,c);
				quotactlname((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_rtprio) {
				(void)putchar('(');
				rtprioname((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS___semctl) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				semctlname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_semget) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				semgetname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_msgctl) {
				print_number(ip,narg,c);
				shmctlname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_shmat) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				shmatname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_shmctl) {
				print_number(ip,narg,c);
				shmctlname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_minherit) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				minheritname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_rfork) {
				(void)putchar('(');
				rforkname((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_lio_listio) {
				(void)putchar('(');
				lio_listioname((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_mlockall) {
				(void)putchar('(');
				mlockallname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_sched_setscheduler) {
				print_number(ip,narg,c);
				schedpolicyname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_sched_get_priority_max ||
				   ktr->ktr_code == SYS_sched_get_priority_min) {
				(void)putchar('(');
				schedpolicyname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_sendfile) {
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				print_number(ip,narg,c);
				sendfileflagsname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_kldsym) {
				print_number(ip,narg,c);
				kldsymcmdname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_sigprocmask) {
				(void)putchar('(');
				sigprocmaskhowname((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS___acl_get_file ||
				   ktr->ktr_code == SYS___acl_set_file ||
				   ktr->ktr_code == SYS___acl_get_fd ||
				   ktr->ktr_code == SYS___acl_set_fd ||
				   ktr->ktr_code == SYS___acl_delete_file ||
				   ktr->ktr_code == SYS___acl_delete_fd ||
				   ktr->ktr_code == SYS___acl_aclcheck_file ||
				   ktr->ktr_code == SYS___acl_aclcheck_fd) {
				print_number(ip,narg,c);
				acltypename((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_sigaction) {
				(void)putchar('(');
				signame((int)*ip);
				ip++;
				narg--;
				c = ',';
			} else if (ktr->ktr_code == SYS_extattrctl) {
				print_number(ip,narg,c);
				extattrctlname((int)*ip);
				ip++;
				narg--;
			} else if (ktr->ktr_code == SYS_ptrace) {
				if (*ip < (register_t)(sizeof(ptrace_ops) /
				    sizeof(ptrace_ops[0])) && *ip >= 0)
					(void)printf("(%s", ptrace_ops[*ip]);
#ifdef PT_GETREGS
				else if (*ip == PT_GETREGS)
					(void)printf("(%s", "PT_GETREGS");
#endif
#ifdef PT_SETREGS
				else if (*ip == PT_SETREGS)
					(void)printf("(%s", "PT_SETREGS");
#endif
#ifdef PT_GETFPREGS
				else if (*ip == PT_GETFPREGS)
					(void)printf("(%s", "PT_GETFPREGS");
#endif
#ifdef PT_SETFPREGS
				else if (*ip == PT_SETFPREGS)
					(void)printf("(%s", "PT_SETFPREGS");
#endif
#ifdef PT_GETDBREGS
				else if (*ip == PT_GETDBREGS)
					(void)printf("(%s", "PT_GETDBREGS");
#endif
#ifdef PT_SETDBREGS
				else if (*ip == PT_SETDBREGS)
					(void)printf("(%s", "PT_SETDBREGS");
#endif
				else
					(void)printf("(%ld", (long)*ip);
				c = ',';
				ip++;
				narg--;
			}
		}
		while (narg > 0) {
			print_number(ip,narg,c);
		}
		(void)putchar(')');
	}
	(void)putchar('\n');
}
예제 #20
0
/*
 * Start up the process with the given args
 */
INTERNAL int
start_agent(AGENT_REQ *areq, char *cmd, char *args, int *retpid) {
	int   argc;
	char *argv[MAX_ARGS];
	char  hostname[AGENTD_NAMELEN];
	int   childpid;
	int   pid, exitstat;
	int   pipeout[2], pipeerr[2];
	int   rc;
	EVENT_AGENTD_STAT estat;
	EVENT_AGENTD_LOG  elogout, elogerr;
	char  msg[200];
	char  cmdpath[PATHLEN];

	if (WorkDir) make_path(cmdpath, ExecPath, cmd);
	else         strcpy(cmdpath, cmd);

	argv[0] = cmd;
	argc    = 1;

	if (Verbose) printf("0: %s (%s)\n", argv[0], cmdpath);
	rc = parse_args(args, argv, 1);
	if (rc < 0) {
		return(0);
	}
	argc = rc;

/**************************/
/****** START DEBUG *******/
#ifdef FAKE_THIS_FOR_DEBUGGING
printf("start_agent: sleeping\n");
	if (areq) {
		areq->status = AGENTD_AGENT_RUNNING;
		areq->pid    = 9999999;

		estat.reqseq  = EventSeq(areq->ereq);
		estat.tag     = areq->ereq.tag;
		estat.reqtype = AGENTD_CTL_START;
		estat.result  = 9999999;
		estat.rstatus = AGENTD_STATUS_OK;
		SEND(EventFrom(areq->ereq), AGENTD_STAT, estat);
	}
sleep(10);
	if (areq) {
		areq->status = AGENTD_AGENT_EXIT;

		estat.result  = 0;
		estat.rstatus = AGENTD_AGENT_EXIT;
		SEND(EventFrom(areq->ereq), AGENTD_STAT, estat);
	}
printf("start_agent: exiting\n");
return(AGENTD_STATUS_OK);
#endif
/******** END DEBUG *******/
/**************************/

	if (pipe(pipeout) != SYS_OK) {
		fprintf(stderr, "start_agent: couldn't create stdout pipe\n");
		perror("start_agent");
		return(AGENTD_STATUS_RUNERR);
	}
	if (pipe(pipeerr) != SYS_OK) {
		fprintf(stderr, "start_agent: couldn't create stderr pipe\n");
		perror("start_agent");
		return(AGENTD_STATUS_RUNERR);
	}

	childpid = fork();
	if (childpid < 0) {        /* Error occurred */
		fprintf(stderr, "start_agent: fork failed\n");
		perror("start_agent");

		close(pipeout[0]);
		close(pipeout[1]);
		close(pipeerr[0]);
		close(pipeerr[1]);

		return(AGENTD_STATUS_RUNERR);
	}

	/*
	 * Exec command from newly forked process
	 */
	if (childpid == 0) {       /* Child process */
		int   fdin;
		int   argc;
		int   rc;

	   /****
		event_exit_();
	    ****/

		if (WorkDir) chdir(WorkPath);

		/* stdin */
		fdin = open("/dev/null", O_RDONLY);
		dup2(fdin, 0);
		close(fdin);

		/* stdout */
		rc = dup2(pipeout[1], 1);
		close(pipeout[0]);
		close(pipeout[1]);
		if (rc < 0) printf("start_agent: couldn't dup pipe as stdout");

		/* stderr */
		rc = dup2(pipeerr[1], 2);
		close(pipeerr[0]);
		close(pipeerr[1]);
		if (rc < 0) printf("start_agent: couldn't dup pipe as stderr");

		/* Create a new process group */
		setpgrp();

		fprintf(stderr,
			"agentd: child proc %d, pgrp %d execing %s\n",
			 getpid(), getpgrp(), cmd);

		execv(cmdpath, argv);

		/* If exec returns it means an error occurred */
		close(0);
		close(1);
		close(2);

		exit(AGENTD_STATUS_RUNERR);
	}

	signal(SIGABRT, SIG_IGN);

	if (Verbose) printf("start_agent: created child process %d\n", childpid);

	/* Report startup status to requester */
	if (areq) {
		areq->status = AGENTD_AGENT_RUNNING;
		areq->pid    = childpid;

		estat.reqseq  = EventSeq(areq->ereq);
		estat.tag     = areq->ereq.tag;
		estat.reqtype = AGENTD_CTL_START;
		estat.result  = childpid;
		estat.rstatus = AGENTD_STATUS_OK;
		SEND(EventFrom(areq->ereq), AGENTD_STAT, estat);
	}

	gethostname(hostname, sizeof(hostname));

	/* Set up stderr */
	elogerr.head.to = EVENT_BCAST_NOTME;
	elogerr.type    = AGENTD_LOG_STDERR;
	elogerr.flags   = pipeerr[0];
	elogerr.pid     = childpid;
	strcpy(elogerr.hostname, hostname);
	strcpy(elogerr.program,  cmd);

	/* Start reader thread and wait for it to initialize */
	if (Verbose) printf("start_agent: starting reader thread for stderr\n");
	mp_task(reader, &elogerr, 0);
	mp_decsema(ReadInit);

	/* Broadcast a message */
	sprintf(elogerr.msg, "agentd: agent started as pid %d\n", childpid);
	SEND(EVENT_BCAST_NOTME, AGENTD_LOG, elogerr);

	/* Now do the same for stdout */
	elogout.head.to = EVENT_BCAST_NOTME;
	elogout.type    = AGENTD_LOG_STDOUT;
	elogout.flags   = pipeout[0];
	elogout.pid     = childpid;
	strcpy(elogout.hostname, hostname);
	strcpy(elogout.program,  cmd);

	if (Verbose) printf("start_agent: starting reader thread for stdout\n");
	mp_task(reader, &elogout, 0);
	mp_decsema(ReadInit);

	/* Wait for child (agent) process to exit */
	if (Verbose) printf("start_agent: waiting for agent proc %d\n", childpid);
	pid = waitpid(childpid, &exitstat, 0);
	if (pid <= 0) {
		perror("start_agent: waitpid");
	}

	if (WIFSIGNALED(exitstat))
	   sprintf(msg, "agent %d exited on signal %s with rc %d",
		childpid,
		signame(WTERMSIG(exitstat)),
		WEXITSTATUS(exitstat));
	else
	   sprintf(msg, "agent %d exited normally with rc %d",
		childpid, WEXITSTATUS(exitstat));

	if (Verbose) printf("start_agent: %s\n", msg);

	/* Set exit and write to pipe to wake up readers */
	mp_lock(Exitlock);

	Exit = childpid;

	sleep(5); /* delay to let things quiesce */

	write(pipeout[1], EofStr, strlen(EofStr)+1);
	write(pipeerr[1], EofStr, strlen(EofStr)+1);

	if (Verbose) printf("start_agent: %d.%d waiting for 2 %d.readers to exit\n", getpid(), mp_gettid(), childpid);
	mp_decsema(Exitwait);
	if (Verbose) printf("start_agent: %d.%d waiting for 1 %d.reader to exit\n", getpid(), mp_gettid(), childpid);
	mp_decsema(Exitwait);
	if (Verbose) printf("start_agent: %d.%d all %d.readers exited\n", getpid(), mp_gettid(), childpid);

	Exit = 0;
	mp_unlock(Exitlock);

	/* Broadcast a message */
	sprintf(elogerr.msg, "agentd: %s\n", msg);
	SEND(EVENT_BCAST_NOTME, AGENTD_LOG, elogerr);

	close(pipeout[0]);
	close(pipeout[1]);
	close(pipeerr[0]);
	close(pipeerr[1]);

	/*
	 * Report exit status back to requester
	 */
	if (areq) {
		areq->status = AGENTD_AGENT_EXIT;

		estat.result  = exitstat;
		estat.rstatus = AGENTD_AGENT_EXIT;
		SEND(EventFrom(areq->ereq), AGENTD_STAT, estat);
	}

	if (retpid) *retpid = childpid;

	return(AGENTD_STATUS_OK);
}
예제 #21
0
// ######################################################################
int main(const int argc, const char **argv)
{
  MYLOGVERB = LOG_INFO;  // suppress debug messages

  volatile int signum = 0;
  catchsignals(&signum);

  ModelManager manager("Test Motion Energy");

  nub::ref<InputFrameSeries> ifs(new InputFrameSeries(manager));
  manager.addSubComponent(ifs);

  nub::ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager));
  manager.addSubComponent(ofs);

  nub::ref<FoeDetector> fd(new FoeDetector(manager));
  manager.addSubComponent(fd);

  if (manager.parseCommandLine((const int)argc, (const char**)argv,
                               "<stimuli> <options>", 0, 9) == false)
    return(1);

  fd->reset(NUM_PYR_LEVEL, NUM_DIRS, NUM_SPEEDS);

  std::string stimuli("Image");
  if(manager.numExtraArgs() > 0)
    stimuli = manager.getExtraArgAs<std::string>(0);
  LINFO("Stimuli: %s", stimuli.c_str());

  manager.start();

  Timer timer(1000000);
  timer.reset();  // reset the timer
  int frame = 0;

  PauseWaiter p;

  uint step; step = 0;

  // to get to the good part
  //for(uint i = 0; i < 50; i++) //was 25
  //  ifs->updateNext();

  // get ground truth file 
  std::string gtFilename
    ("/lab/tmpib/u/siagian/neuroscience/Data/FOE/driving_nat_Browning.txt");
  std::vector<Point2D<int> > gt = getGT(gtFilename);
  int ldpos = gtFilename.find_last_of('.');
  std::string prefix = gtFilename.substr(0, ldpos);

  // for finding ground truth
  rutz::shared_ptr<XWinManaged> win;
  
  float totalErr = 0.0;

  std::vector<std::string> args;
  for(uint i = 0; i < manager.numExtraArgs(); i++)
    args.push_back(manager.getExtraArgAs<std::string>(i)); 

  Image<byte> prevLum;
  Image<PixRGB<byte> > prevImage;
  Image<PixRGB<byte> > prevImage2;
  while (1)
    {
      if (signum != 0)
        {
          LINFO("quitting because %s was caught", signame(signum));
          break;
        }

      if (ofs->becameVoid())
        {
          LINFO("quitting because output stream was closed or became void");
          break;
        }

      if (p.checkPause())
        continue;

      const FrameState is = ifs->updateNext();
      if (is == FRAME_COMPLETE) break; // done receiving frames

      Image< PixRGB<byte> > input = ifs->readRGB();
      if(frame == 0) 
        {
          uint width  = input.getWidth();
          uint height = input.getHeight();
          win.reset(new XWinManaged(Dims(width, height), 0, 0, "GT"));
        }

      // empty image signifies end-of-stream
      if (!input.initialized()) break;
      Image<byte> lum = luminance(input);
      Point2D<float> pshift(0.0,0.0); 
      if(step != 0)
        {
          // calculate planar shift using SIFT 
          lum = calculateShift(lum,prevLum, ofs);
        }
      if( manager.numExtraArgs() > 0)
        lum = getImage(stimuli, args, fd, step);

      // for saving videos
      prevImage2 = prevImage;
      prevImage  = input;

      if (!lum.initialized()) break; step++;

      // compute the focus of expansion (FOE)
      Point2D<int> foe = fd->getFoe(lum, FOE_METHOD_TEMPLATE, false);
      //Point2D<int> foe = fd->getFoe(lum, FOE_METHOD_AVERAGE);
      LINFO("[%d]Foe: %d %d", frame, foe.i, foe.j);

      // illustration of the size of the receptive field
      if(!stimuli.compare("ShowRF"))
        {
          uint rfI = 44;
          uint rfJ = 152;
          lum.setVal(rfI, rfJ, 300.0F);      
          drawRect(lum, Rectangle::tlbrI(144,36,159,51), byte(255));
          drawRect(lum, Rectangle::tlbrI(148,40,155,47), byte(255));
          
          drawRect(lum, Rectangle::tlbrI(rfJ-8, rfI-8, rfJ+8, rfI+8), byte(255));
          drawRect(lum, Rectangle::tlbrI(rfJ-16,rfI-16,rfJ+16,rfI+16), byte(255));
        }

      ofs->writeGrayLayout(fd->getMTfeaturesDisplay(lum), "MT Features",
                           FrameInfo("motion energy output images", SRC_POS));

      // write the file
      if(frame >= 4)
        {
          float err = foe.distance(gt[frame-2]); 
          totalErr += err;
          LINFO("Foe: %d %d: GT: %d %d --> %f --> avg: %f", 
                foe.i, foe.j, gt[frame-2].i, gt[frame-2].j, 
                err, totalErr/(frame-3));

          Image<PixRGB<byte> > simg = prevImage2;
          drawCross(simg, foe        , PixRGB<byte>(0,255,0), 10, 2);
          drawCross(simg, gt[frame-2], PixRGB<byte>(255,0,0), 10, 2);
          win->drawImage(simg,0,0);
          //Raster::WriteRGB(simg, sformat("%s_STnPS_%06d.ppm", prefix.c_str(), frame-2));
        }

      //ofs->writeGrayLayout
      //  (lum, "test-FOE Main", FrameInfo("foe output", SRC_POS));
      const FrameState os = ofs->updateNext();
      //LINFO("frame[%d]: %8.3f %8.3f", frame, pshift.i, pshift.j); 
      Raster::waitForKey();

      if (os == FRAME_FINAL)
        break;

      prevLum  = lum;
      frame++;
    }

  LINFO("%d frames in %gs (%.2ffps)\n", 
        frame, timer.getSecs(), frame / timer.getSecs());

  // stop all our ModelComponents
  manager.stop();

  // all done!
  return 0;

}
예제 #22
0
// ######################################################################
int Streamer::tryRun(const int argc, const char** argv,
                     const char* extraArgsDescription,
                     const int minExtraArgs, const int maxExtraArgs)
{
  volatile int signum = 0;
  catchsignals(&signum);

  if (itsManager->parseCommandLine(argc, argv, extraArgsDescription,
                                   minExtraArgs, maxExtraArgs) == false)
    return(1);

  this->handleExtraArgs(*itsManager);

  itsManager->start();

  itsIfs->startStream();

  int c = 0;

  PauseWaiter p;

  while (true)
    {
      if (signum != 0)
        {
          LINFO("quitting because %s was caught", signame(signum));
          return -1;
        }

      if (itsOfs->becameVoid())
        {
          LINFO("quitting because output stream was closed or became void");
          return 0;
        }

      if (p.checkPause())
        continue;

      const FrameState is = itsIfs->updateNext();
      if (is == FRAME_COMPLETE)
        break;

      GenericFrame input = itsIfs->readFrame();
      if (!input.initialized())
        break;

      const FrameState os = itsOfs->updateNext();

      this->onFrame(input, *itsOfs, itsIfs->frame());

      if (os == FRAME_FINAL)
        break;

      LDEBUG("frame %d", c++);

      if (itsIfs->shouldWait() || itsOfs->shouldWait())
        Raster::waitForKey();
    }

  itsManager->stop();

  return 0;
}
예제 #23
0
파일: signal.c 프로젝트: lineprinter/strace
void
printsignal(int nr)
{
	tprints(signame(nr));
}
예제 #24
0
static void myhandler( int s)
  {
  resethandlers();
  os_fatal("Signal %d received %s",s,signame(s));
  }