Esempio n. 1
0
int
ar_next(void)
{
	static char *arcbuf;
	char buf[PAXPATHLEN+2];
	sigset_t o_mask;

	/*
	 * WE MUST CLOSE THE DEVICE. A lot of devices must see last close, (so
	 * things like writing EOF etc will be done) (Watch out ar_close() can
	 * also be called via a signal handler, so we must prevent a race.
	 */
	if (sigprocmask(SIG_BLOCK, &s_mask, &o_mask) < 0)
		syswarn(0, errno, "Unable to set signal mask");
	ar_close();
	if (sigprocmask(SIG_SETMASK, &o_mask, NULL) < 0)
		syswarn(0, errno, "Unable to restore signal mask");

	if (done || !wr_trail || strcmp(NM_TAR, argv0) == 0)
		return(-1);

	tty_prnt("\nATTENTION! %s archive volume change required.\n", argv0);

	/*
	 * if i/o is on stdin or stdout, we cannot reopen it (we do not know
	 * the name), the user will be forced to type it in.
	 */
	if (strcmp(arcname, stdo) && strcmp(arcname, stdn) && (artyp != ISREG)
	    && (artyp != ISPIPE)) {
		if (artyp == ISTAPE) {
			tty_prnt("%s ready for archive tape volume: %d\n",
				arcname, arvol);
			tty_prnt("Load the NEXT TAPE on the tape drive");
		} else {
			tty_prnt("%s ready for archive volume: %d\n",
				arcname, arvol);
			tty_prnt("Load the NEXT STORAGE MEDIA (if required)");
		}

		if ((act == ARCHIVE) || (act == APPND))
			tty_prnt(" and make sure it is WRITE ENABLED.\n");
		else
			tty_prnt("\n");

		for(;;) {
			tty_prnt("Type \"y\" to continue, \".\" to quit %s,",
				argv0);
			tty_prnt(" or \"s\" to switch to new device.\nIf you");
			tty_prnt(" cannot change storage media, type \"s\"\n");
			tty_prnt("Is the device ready and online? > ");

			if ((tty_read(buf,sizeof(buf))<0) || !strcmp(buf,".")){
				done = 1;
				lstrval = -1;
				tty_prnt("Quitting %s!\n", argv0);
				vfpart = 0;
				return(-1);
			}

			if ((buf[0] == '\0') || (buf[1] != '\0')) {
				tty_prnt("%s unknown command, try again\n",buf);
				continue;
			}

			switch (buf[0]) {
			case 'y':
			case 'Y':
				/*
				 * we are to continue with the same device
				 */
				if (ar_open(arcname) >= 0)
					return(0);
				tty_prnt("Cannot re-open %s, try again\n",
					arcname);
				continue;
			case 's':
			case 'S':
				/*
				 * user wants to open a different device
				 */
				tty_prnt("Switching to a different archive\n");
				break;
			default:
				tty_prnt("%s unknown command, try again\n",buf);
				continue;
			}
			break;
		}
	} else
		tty_prnt("Ready for archive volume: %d\n", arvol);

	/*
	 * have to go to a different archive
	 */
	for (;;) {
		tty_prnt("Input archive name or \".\" to quit %s.\n", argv0);
		tty_prnt("Archive name > ");

		if ((tty_read(buf, sizeof(buf)) < 0) || !strcmp(buf, ".")) {
			done = 1;
			lstrval = -1;
			tty_prnt("Quitting %s!\n", argv0);
			vfpart = 0;
			return(-1);
		}
		if (buf[0] == '\0') {
			tty_prnt("Empty file name, try again\n");
			continue;
		}
		if (!strcmp(buf, "..")) {
			tty_prnt("Illegal file name: .. try again\n");
			continue;
		}
		if (strlen(buf) > PAXPATHLEN) {
			tty_prnt("File name too long, try again\n");
			continue;
		}

		/*
		 * try to open new archive
		 */
		if (ar_open(buf) >= 0) {
			free(arcbuf);
			if ((arcbuf = strdup(buf)) == NULL) {
				done = 1;
				lstrval = -1;
				paxwarn(0, "Cannot save archive name.");
				return(-1);
			}
			arcname = arcbuf;
			break;
		}
		tty_prnt("Cannot open %s, try again\n", buf);
		continue;
	}
	return(0);
}
Esempio n. 2
0
int main(int argc, char **argv)
{
	int fp, fd;
	int res;
	struct flock fl;
	sigset_t set, oldset;
    pid_t pid;

    int runmode, opt;
    const char *lockfile;

    lockfile = get_perf_alloc_lockfile();
    runmode = RUN_FOREGROUND;
    while ((opt = getopt(argc, argv, "dDf:hv")) != -1) {
        switch (opt) {
            case 'd':
                runmode = RUN_AS_DAEMON;
                break;
            case 'D':
                runmode = RUN_FOREGROUND;
                break;
            case 'f':
                lockfile = optarg;
                break;
            case 'h':
                usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
            case 'v':
                printf("perfalloc " VERSION "\n" );
                exit(EXIT_SUCCESS);
                break;
            default: /* '?' */
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    if( optind < argc )
    {
        runmode = RUN_USERCOMMAND;
    }

    if(RUN_AS_DAEMON == runmode)
	{
		if( -1 == daemon(0,0) ) {
			perror("fork");
			exit(EXIT_FAILURE);
		}
	}
    else if (RUN_USERCOMMAND == runmode)
    {
        pid = fork();
        if (pid == -1) 
        {
            perror("fork");
            exit(EXIT_FAILURE);
        }
        if (pid != 0) 
        {     /* Parent - execute the given command. */
            execvp(argv[optind], &argv[optind]);
            perror(argv[optind]);
            exit(EXIT_FAILURE);
        }

        /* Child - make sure that kernel signals when parent dies */
        prctl(PR_SET_PDEATHSIG, SIGHUP);

        if ( -1 == chdir("/") ) {
            perror("chdir");
            /* carry on even if chdir fails ..*/
        }
             
        if ((fd = open("/dev/null", O_RDWR, 0)) != -1) 
        {
            (void) dup2(fd, STDIN_FILENO);
            (void) dup2(fd, STDOUT_FILENO);
            (void) dup2(fd, STDERR_FILENO);
            if (fd > 2)
                close(fd);
        }
    }

	fp = open(lockfile, O_RDONLY);

	if( fp < 0 ) {
		fprintf(stderr, "open %s: %s\n", lockfile, strerror(errno) );
		exit(EXIT_FAILURE);  
	}

	fl.l_type = F_RDLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 1;

	res = fcntl(fp, F_SETLK, &fl);

	if( res == -1 )
	{
		perror("fcntl");
		close(fp);
		exit(EXIT_FAILURE);  
	}

	signal (SIGINT, handler);
	signal (SIGHUP, handler);

	sigemptyset (&set);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGHUP);

	sigprocmask(SIG_BLOCK, &set, &oldset);

	while(running)
	{
		sigsuspend(&oldset);
	}

	sigprocmask(SIG_UNBLOCK, &set, NULL);

	fl.l_type = F_UNLCK;
	(void) fcntl(fp, F_SETLK, &fl);
	(void) close(fp);
    free_perf_alloc_lockfile();

	return 0;
}
Esempio n. 3
0
/*
 * handler()
 *
 * 	A signal handler that understands which test case is currently
 * 	being executed and compares the current conditions to the ones it
 * 	expects (based on the test case number).
 */
void handler(int sig, siginfo_t * sip, void *ucp)
{
	struct sigaction oact;
	int err;
	sigset_t nmask, omask;

	/*
	 * Get sigaction setting
	 */
	err = sigaction(SIGUSR1, NULL, &oact);

	if (err == -1) {
		perror("sigaction");
		return;
	}

	/*
	 * Get current signal mask
	 */
	sigemptyset(&nmask);
	sigemptyset(&omask);
	err = sigprocmask(SIG_BLOCK, &nmask, &omask);
	if (err == -1) {
		perror("sigprocmask");
		tst_resm(TWARN, "sigprocmask() failed");
		return;
	}

	switch (testcase_no) {
	case 1:
		/*
		 * SA_RESETHAND and SA_SIGINFO were set. SA_SIGINFO should
		 * be clear in Linux. In Linux kernel, SA_SIGINFO is not
		 * cleared in psig().
		 */
		if (!(oact.sa_flags & SA_SIGINFO)) {
			tst_resm(TFAIL, "SA_RESETHAND should not "
				 "cause SA_SIGINFO to be cleared, but it was.");
			return;
		}
		if (sip == NULL) {
			tst_resm(TFAIL, "siginfo should not be NULL");
			return;
		}
		tst_resm(TPASS, "SA_RESETHAND did not "
			 "cause SA_SIGINFO to be cleared");
		break;

	case 2:
		/*
		 * In Linux, SA_RESETHAND doesn't imply SA_NODEFER; sig
		 * should not be masked.  The testcase should pass if
		 * SA_NODEFER is not masked, ie. if SA_NODEFER is a member
		 * of the signal list
		 */
		if (sigismember(&omask, sig) == 0) {
			tst_resm(TFAIL, "SA_RESETHAND should cause sig to"
				 "be masked when the handler executes.");
			return;
		}
		tst_resm(TPASS, "SA_RESETHAND was masked when handler "
			 "executed");
		break;

	case 3:
		/*
		 * SA_RESETHAND implies SA_NODEFER unless sa_mask already
		 * included sig.
		 */
		if (!sigismember(&omask, sig)) {
			tst_resm(TFAIL, "sig should continue to be masked"
				 "because sa_mask originally contained sig.");
			return;
		}
		tst_resm(TPASS, "sig has been masked "
			 "because sa_mask originally contained sig");
		break;

	case 4:
		/*
		 * A signal generated from a mechanism that does not provide
		 * siginfo should invoke the handler with a non-NULL siginfo
		 * pointer.
		 */
		if (sip == NULL) {
			tst_resm(TFAIL, "siginfo pointer should not be NULL");
			return;
		}
		tst_resm(TPASS, "siginfo pointer non NULL");
		break;

	default:
		tst_resm(TFAIL, "invalid test case number: %d", testcase_no);
		exit(1);
	}
}
Esempio n. 4
0
static void pthread_initialize(void)
{
  struct sigaction sa;
  sigset_t mask;
#ifdef __ARCH_USE_MMU__
  struct rlimit limit;
  rlim_t max_stack;
#endif

  /* If already done (e.g. by a constructor called earlier!), bail out */
  if (__pthread_initial_thread_bos != NULL) return;
#ifdef TEST_FOR_COMPARE_AND_SWAP
  /* Test if compare-and-swap is available */
  __pthread_has_cas = compare_and_swap_is_available();
#endif
  /* For the initial stack, reserve at least STACK_SIZE bytes of stack
     below the current stack address, and align that on a
     STACK_SIZE boundary. */
  __pthread_initial_thread_bos =
    (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
  /* Update the descriptor for the initial thread. */
  __pthread_initial_thread.p_pid = getpid();
  /* If we have special thread_self processing, initialize that for the
     main thread now.  */
#ifdef INIT_THREAD_SELF
  INIT_THREAD_SELF(&__pthread_initial_thread, 0);
#endif
  /* The errno/h_errno variable of the main thread are the global ones.  */
  __pthread_initial_thread.p_errnop = &_errno;
  __pthread_initial_thread.p_h_errnop = &_h_errno;

#ifdef __UCLIBC_HAS_XLOCALE__
  /* The locale of the main thread is the current locale in use. */
  __pthread_initial_thread.locale = __curlocale_var;
#endif /* __UCLIBC_HAS_XLOCALE__ */

 {			   /* uClibc-specific stdio initialization for threads. */
	 FILE *fp;

	 _stdio_user_locking = 0;	/* 2 if threading not initialized */
	 for (fp = _stdio_openlist; fp != NULL; fp = fp->__nextopen) {
		 if (fp->__user_locking != 1) {
			 fp->__user_locking = 0;
		 }
	 }
 }

  /* Play with the stack size limit to make sure that no stack ever grows
     beyond STACK_SIZE minus two pages (one page for the thread descriptor
     immediately beyond, and one page to act as a guard page). */

#ifdef __ARCH_USE_MMU__
  /* We cannot allocate a huge chunk of memory to mmap all thread stacks later
   * on a non-MMU system. Thus, we don't need the rlimit either. -StS */
  getrlimit(RLIMIT_STACK, &limit);
  max_stack = STACK_SIZE - 2 * getpagesize();
  if (limit.rlim_cur > max_stack) {
    limit.rlim_cur = max_stack;
    setrlimit(RLIMIT_STACK, &limit);
  }
#else
  /* For non-MMU, the initial thread stack can reside anywhere in memory.
   * We don't have a way of knowing where the kernel started things -- top
   * or bottom (well, that isn't exactly true, but the solution is fairly
   * complex and error prone).  All we can determine here is an address
   * that lies within that stack.  Save that address as a reference so that
   * as other thread stacks are created, we can adjust the estimated bounds
   * of the initial thread's stack appropriately.
   *
   * This checking is handled in NOMMU_INITIAL_THREAD_BOUNDS(), so see that
   * for a few more details.
   */
  __pthread_initial_thread_mid = CURRENT_STACK_FRAME;
  __pthread_initial_thread_tos = (char *) -1;
  __pthread_initial_thread_bos = (char *) 1; /* set it non-zero so we know we have been here */
  PDEBUG("initial thread stack bounds: bos=%p, tos=%p\n",
	 __pthread_initial_thread_bos, __pthread_initial_thread_tos);
#endif /* __ARCH_USE_MMU__ */

  /* Setup signal handlers for the initial thread.
     Since signal handlers are shared between threads, these settings
     will be inherited by all other threads. */
  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = pthread_handle_sigrestart;
  __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  sa.sa_handler = pthread_handle_sigcancel;
  sigaddset(&sa.sa_mask, __pthread_sig_restart);
  __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  if (__pthread_sig_debug > 0) {
      sa.sa_handler = pthread_handle_sigdebug;
      __sigemptyset(&sa.sa_mask);
      __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  }
  /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  __sigemptyset(&mask);
  sigaddset(&mask, __pthread_sig_restart);
  sigprocmask(SIG_BLOCK, &mask, NULL);
  /* And unblock __pthread_sig_cancel if it has been blocked. */
  sigdelset(&mask, __pthread_sig_restart);
  sigaddset(&mask, __pthread_sig_cancel);
  sigprocmask(SIG_UNBLOCK, &mask, NULL);
  /* Register an exit function to kill all other threads. */
  /* Do it early so that user-registered atexit functions are called
     before pthread_onexit_process. */
  on_exit(pthread_onexit_process, NULL);
}
Esempio n. 5
0
void Sigprocmask(int method, sigset_t *mask, sigset_t *oldmask) {
    if (sigprocmask(method, mask, oldmask)) {
        unix_error("Sigprocmask error");
    }
}
Esempio n. 6
0
void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    char              *title;
    u_char            *p;
    size_t             size;
    ngx_int_t          i;
    ngx_uint_t         n, sigio;
    sigset_t           set;
    struct itimerval   itv;
    ngx_uint_t         live;
    ngx_msec_t         delay;
    ngx_listening_t   *ls;
    ngx_core_conf_t   *ccf;
    struct rlimit     rlmt;

    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigaddset(&set, SIGINT);
    sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

    if (sigprocmask(SIG_BLOCK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    sigemptyset(&set);


    size = sizeof(master_process);

    for (i = 0; i < ngx_argc; i++) {
        size += ngx_strlen(ngx_argv[i]) + 1;
    }

    title = ngx_pnalloc(cycle->pool, size);

    p = ngx_cpymem(title, master_process, sizeof(master_process) - 1);
    for (i = 0; i < ngx_argc; i++) {
        *p++ = ' ';
        p = ngx_cpystrn(p, (u_char *) ngx_argv[i], size);
    }

    ngx_setproctitle(title);


    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    ngx_start_worker_processes(cycle, ccf->worker_processes,
                               NGX_PROCESS_RESPAWN);
    /* The directives such as "user", "rlimit_core", etc. should also be
     * effective on master process. Changed by Zimbra
     */
    if (ccf->rlimit_nofile != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_nofile;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_nofile;

        if (setrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_NOFILE, %i) failed",
                          ccf->rlimit_nofile);
        }
    }

    if (ccf->rlimit_core != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_core;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_core;

        if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_CORE, %O) failed",
                          ccf->rlimit_core);
        }
    }

#ifdef RLIMIT_SIGPENDING
    if (ccf->rlimit_sigpending != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_sigpending;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_sigpending;

        if (setrlimit(RLIMIT_SIGPENDING, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_SIGPENDING, %i) failed",
                          ccf->rlimit_sigpending);
        }
    }
#endif

    if (geteuid() == 0) {
        if (setgid(ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setgid(%d) failed", ccf->group);
            /* fatal */
            exit(2);
        }

        if (initgroups(ccf->username, ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "initgroups(%s, %d) failed",
                          ccf->username, ccf->group);
        }

        if (setuid(ccf->user) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setuid(%d) failed", ccf->user);
            /* fatal */
            exit(2);
        }
    }
    /* end change by Zimbra */
    ngx_start_cache_manager_processes(cycle, 0);

    ngx_new_binary = 0;
    delay = 0;
    sigio = 0;
    live = 1;

    for ( ;; ) {
        if (delay) {
            if (ngx_sigalrm) {
                sigio = 0;
                delay *= 2;
                ngx_sigalrm = 0;
            }

            ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                           "termination cycle: %d", delay);

            itv.it_interval.tv_sec = 0;
            itv.it_interval.tv_usec = 0;
            itv.it_value.tv_sec = delay / 1000;
            itv.it_value.tv_usec = (delay % 1000 ) * 1000;

            if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                              "setitimer() failed");
            }
        }

        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend");

        sigsuspend(&set);

        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                       "wake up, sigio %i", sigio);

        if (ngx_reap) {
            ngx_reap = 0;
            ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "reap children");

            live = ngx_reap_children(cycle);
        }

        if (!live && (ngx_terminate || ngx_quit)) {
            ngx_master_process_exit(cycle);
        }

        if (ngx_terminate) {
            if (delay == 0) {
                delay = 50;
            }

            if (sigio) {
                sigio--;
                continue;
            }

            sigio = ccf->worker_processes + 2 /* cache processes */;

            if (delay > 1000) {
                ngx_signal_worker_processes(cycle, SIGKILL);
            } else {
                ngx_signal_worker_processes(cycle,
                                       ngx_signal_value(NGX_TERMINATE_SIGNAL));
            }

            continue;
        }

        if (ngx_quit) {
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));

            ls = cycle->listening.elts;
            for (n = 0; n < cycle->listening.nelts; n++) {
                if (ngx_close_socket(ls[n].fd) == -1) {
                    ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno,
                                  ngx_close_socket_n " %V failed",
                                  &ls[n].addr_text);
                }
            }
            cycle->listening.nelts = 0;

            continue;
        }

        if (ngx_reconfigure) {
            ngx_reconfigure = 0;

            if (ngx_new_binary) {
                ngx_start_worker_processes(cycle, ccf->worker_processes,
                                           NGX_PROCESS_RESPAWN);
                ngx_start_cache_manager_processes(cycle, 0);
                ngx_noaccepting = 0;

                continue;
            }

            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

            cycle = ngx_init_cycle(cycle);
            if (cycle == NULL) {
                cycle = (ngx_cycle_t *) ngx_cycle;
                continue;
            }

            ngx_cycle = cycle;
            ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx,
                                                   ngx_core_module);
            ngx_start_worker_processes(cycle, ccf->worker_processes,
                                       NGX_PROCESS_JUST_RESPAWN);
            ngx_start_cache_manager_processes(cycle, 1);
            live = 1;
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
        }

        if (ngx_restart) {
            ngx_restart = 0;
            ngx_start_worker_processes(cycle, ccf->worker_processes,
                                       NGX_PROCESS_RESPAWN);
            ngx_start_cache_manager_processes(cycle, 0);
            live = 1;
        }

        if (ngx_reopen) {
            ngx_reopen = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
            ngx_reopen_files(cycle, ccf->user);
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_REOPEN_SIGNAL));
        }

        if (ngx_change_binary) {
            ngx_change_binary = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "changing binary");
            ngx_new_binary = ngx_exec_new_binary(cycle, ngx_argv);
        }

        if (ngx_noaccept) {
            ngx_noaccept = 0;
            ngx_noaccepting = 1;
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
        }
    }
}
Esempio n. 7
0
void do_signal(struct pt_regs *regs)
{
	siginfo_t info;
	int signr;
	struct k_sigaction ka;

	/*
                                             
                                                
                                                   
          
  */
	if (!user_mode(regs))
		return;

	signr = get_signal_to_deliver(&info, &ka, regs, NULL);

	/*                                               
                                                           
                                                             
                                                             
                                                       
                                                          
                                                             
                         
  */
	if (regs->orig_gpr11) {
		int restart = 0;

		switch (regs->gpr[11]) {
		case -ERESTART_RESTARTBLOCK:
		case -ERESTARTNOHAND:
			/*                                       */
			restart = (signr <= 0);
			break;
		case -ERESTARTSYS:
			/*                                      
                             */
			restart = (signr <= 0 || (ka.sa.sa_flags & SA_RESTART));
			break;
		case -ERESTARTNOINTR:
			/*                */
			restart = 1;
			break;
		}

		if (restart) {
			if (regs->gpr[11] == -ERESTART_RESTARTBLOCK)
				regs->gpr[11] = __NR_restart_syscall;
			else
				regs->gpr[11] = regs->orig_gpr11;
			regs->pc -= 4;
		} else {
			regs->gpr[11] = -EINTR;
		}
	}

	if (signr <= 0) {
		/*                                                      
          */
		if (test_thread_flag(TIF_RESTORE_SIGMASK)) {
			clear_thread_flag(TIF_RESTORE_SIGMASK);
			sigprocmask(SIG_SETMASK, &current->saved_sigmask, NULL);
		}

	} else {		/*           */
		sigset_t *oldset;

		if (current_thread_info()->flags & _TIF_RESTORE_SIGMASK)
			oldset = &current->saved_sigmask;
		else
			oldset = &current->blocked;

		/*                                      */
		if (!handle_signal(signr, &info, &ka, oldset, regs)) {
			/*                                               
                                                        
                                                         
                                         */
			clear_thread_flag(TIF_RESTORE_SIGMASK);
		}

		tracehook_signal_handler(signr, &info, &ka, regs,
					 test_thread_flag(TIF_SINGLESTEP));
	}

	return;
}
Esempio n. 8
0
int armour_proc_recover (armour_proc *proc, void *data)
{
    pid_t pid;
    sigset_t set;
    int i, fd;
    (void)data;

    //pid = vfork ();
    pid = fork ();
    
    switch (pid) {
        case -1:
            DWARN ("fork");
            return -1;
        case 0:
            if (proc->flags & ARPROC_SETSID) {
                pid = fork ();
                switch (pid) {
                    case -1:
                        DWARN ("fork");
                        return -1;
                    case 0:
                        setsid (); // TODO check return value
                        break;
                    default:
                        _exit (0);
                        break;
                }
            } else {
                setpgid (0, 0);
            }
            /*
             * remove signal mask
             */
            sigprocmask (SIG_BLOCK, NULL, &set);
            sigprocmask (SIG_UNBLOCK, &set, NULL);

            /*
             * attach file desc. 0, 1 and 2 to whatever files it used
             */
            for (i = 0; i < 3; i++) {
                fd = open (proc->file[i], O_RDWR);
                dup2 (fd, i);
            }
            /*
             * change working and root directory
             */
            chdir (proc->cwd);
            chroot (proc->root);
            /*
             * set uid and gid
             */
            setgid (proc->gid);
            setuid (proc->uid);

            execve (proc->exe, proc->cmdline, proc->environ);
            DWARN ("execve");
            _exit (127); /* exec error! */

        default:
            break;
    }
    return 0;
}
Esempio n. 9
0
int
_eval(char *const argv[], char *path, int timeout, int *ppid)
{
	sigset_t set;
	pid_t pid, ret;
	int status;
	int fd;
	int flags;
	int sig, i;

	switch (pid = fork()) {
	case -1:	/* error */
		perror("fork");
		return errno;
	case 0:	 /* child */
		/* Reset signal handlers set for parent process */
		for (sig = 0; sig < (_NSIG-1); sig++)
			signal(sig, SIG_DFL);

		/* Unblock signals if called from signal handler */
		sigemptyset(&set);
		sigprocmask(SIG_SETMASK, &set, NULL);

		/* Clean up */
		for (i=3; i<256; i++)    // close un-needed fd
			close(i);
		ioctl(0, TIOCNOTTY, 0);	// detach from current process
		setsid();
		
		/* Redirect stdout to <path> */
		if (path) {
			flags = O_WRONLY | O_CREAT;
			if (!strncmp(path, ">>", 2)) {
				/* append to <path> */
				flags |= O_APPEND;
				path += 2;
			} else if (!strncmp(path, ">", 1)) {
				/* overwrite <path> */
				flags |= O_TRUNC;
				path += 1;
			}
			if ((fd = open(path, flags, 0644)) < 0)
				perror(path);
			else {
				dup2(fd, STDOUT_FILENO);
				dup2(fd, STDERR_FILENO);
				close(fd);
			}
		}
		
		/* execute command */
		setenv("PATH", SYS_EXEC_PATH, 1);
		alarm(timeout);
		execvp(argv[0], argv);
		perror(argv[0]);
		exit(errno);
	default:	/* parent */
		if (ppid) {
			*ppid = pid;
			return 0;
		} else {
			do
				ret = waitpid(pid, &status, 0);
			while ((ret == -1) && (errno == EINTR));
			
			if (ret != pid) {
				perror("waitpid");
				return errno;
			}
			if (WIFEXITED(status))
				return WEXITSTATUS(status);
			else
				return status;
		}
	}
}
Esempio n. 10
0
File: start.c Progetto: MSahl/lxc
void lxc_fini(const char *name, struct lxc_handler *handler)
{
	int i, rc;
	pid_t self = getpid();
	char *namespaces[LXC_NS_MAX+1];
	size_t namespace_count = 0;

	/* The STOPPING state is there for future cleanup code
	 * which can take awhile
	 */
	lxc_set_state(name, handler, STOPPING);

	for (i = 0; i < LXC_NS_MAX; i++) {
		if (handler->nsfd[i] != -1) {
			rc = asprintf(&namespaces[namespace_count], "%s:/proc/%d/fd/%d",
			              ns_info[i].proc_name, self, handler->nsfd[i]);
			if (rc == -1) {
				SYSERROR("failed to allocate memory");
				break;
			}
			++namespace_count;
		}
	}
	namespaces[namespace_count] = NULL;

	if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1)) {
		SYSERROR("failed to set environment variable for stop target");
	}
	if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1)) {
		SYSERROR("failed to set environment variable for stop target");
	}

	if (run_lxc_hooks(name, "stop", handler->conf, handler->lxcpath, namespaces))
		ERROR("failed to run stop hooks for container '%s'.", name);

	while (namespace_count--)
		free(namespaces[namespace_count]);
	for (i = 0; i < LXC_NS_MAX; i++) {
		if (handler->nsfd[i] != -1) {
			close(handler->nsfd[i]);
			handler->nsfd[i] = -1;
		}
	}
	lxc_set_state(name, handler, STOPPED);

	if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL)) {
		ERROR("failed to run post-stop hooks for container '%s'.", name);
		if (handler->conf->reboot) {
			WARN("Container will be stopped instead of rebooted.");
			handler->conf->reboot = 0;
			setenv("LXC_TARGET", "stop", 1);
		}
	}

	/* reset mask set by setup_signal_fd */
	if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
		WARN("failed to restore sigprocmask");

	lxc_console_delete(&handler->conf->console);
	lxc_delete_tty(&handler->conf->tty_info);
	close(handler->conf->maincmd_fd);
	handler->conf->maincmd_fd = -1;
	free(handler->name);
	if (handler->ttysock[0] != -1) {
		close(handler->ttysock[0]);
		close(handler->ttysock[1]);
	}

	if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
		lxc_destroy_container_on_signal(handler, name);

	cgroup_destroy(handler);
	free(handler);
}
Esempio n. 11
0
/*
 *----------------------------------------------------------
 * StartUp--
 * 	starts the window manager and setup global data.
 * Called from main() at startup.
 *
 * Side effects:
 * global data declared in main.c is initialized
 *----------------------------------------------------------
 */
void StartUp(Bool defaultScreenOnly)
{
	struct sigaction sig_action;
	int i, j, max;
	char **formats;
	Atom atom[wlengthof(atomNames)];

	/*
	 * Ignore CapsLock in modifiers
	 */
	w_global.shortcut.modifiers_mask = 0xff & ~LockMask;

	getOffendingModifiers();
	/*
	 * Ignore NumLock and ScrollLock too
	 */
	w_global.shortcut.modifiers_mask &= ~(_NumLockMask | _ScrollLockMask);

	memset(&wKeyBindings, 0, sizeof(wKeyBindings));

	w_global.context.client_win = XUniqueContext();
	w_global.context.app_win = XUniqueContext();
	w_global.context.stack = XUniqueContext();

	/*    _XA_VERSION = XInternAtom(dpy, "VERSION", False); */

#ifdef HAVE_XINTERNATOMS
	XInternAtoms(dpy, atomNames, wlengthof(atomNames), False, atom);
#else

	{
		int i;
		for (i = 0; i < wlengthof(atomNames); i++)
			atom[i] = XInternAtom(dpy, atomNames[i], False);
	}
#endif

	w_global.atom.wm.state = atom[0];
	w_global.atom.wm.change_state = atom[1];
	w_global.atom.wm.protocols = atom[2];
	w_global.atom.wm.take_focus = atom[3];
	w_global.atom.wm.delete_window = atom[4];
	w_global.atom.wm.save_yourself = atom[5];
	w_global.atom.wm.client_leader = atom[6];
	w_global.atom.wm.colormap_windows = atom[7];
	w_global.atom.wm.colormap_notify = atom[8];

	w_global.atom.wmaker.menu = atom[9];
	w_global.atom.wmaker.state = atom[10];
	w_global.atom.wmaker.wm_protocols = atom[11];
	w_global.atom.wmaker.wm_function = atom[12];
	w_global.atom.wmaker.noticeboard = atom[13];
	w_global.atom.wmaker.command = atom[14];
	w_global.atom.wmaker.icon_size = atom[15];
	w_global.atom.wmaker.icon_tile = atom[16];

	w_global.atom.gnustep.wm_attr = atom[17];
	w_global.atom.gnustep.wm_miniaturize_window = atom[18];
	w_global.atom.gnustep.titlebar_state = atom[19];

	w_global.atom.wm.ignore_focus_events = atom[20];

#ifdef XDND
	wXDNDInitializeAtoms();
#endif

	/* cursors */
	wPreferences.cursor[WCUR_NORMAL] = None;	/* inherit from root */
	wPreferences.cursor[WCUR_ROOT] = XCreateFontCursor(dpy, XC_left_ptr);
	wPreferences.cursor[WCUR_ARROW] = XCreateFontCursor(dpy, XC_top_left_arrow);
	wPreferences.cursor[WCUR_MOVE] = XCreateFontCursor(dpy, XC_fleur);
	wPreferences.cursor[WCUR_RESIZE] = XCreateFontCursor(dpy, XC_sizing);
	wPreferences.cursor[WCUR_TOPLEFTRESIZE] = XCreateFontCursor(dpy, XC_top_left_corner);
	wPreferences.cursor[WCUR_TOPRIGHTRESIZE] = XCreateFontCursor(dpy, XC_top_right_corner);
	wPreferences.cursor[WCUR_BOTTOMLEFTRESIZE] = XCreateFontCursor(dpy, XC_bottom_left_corner);
	wPreferences.cursor[WCUR_BOTTOMRIGHTRESIZE] = XCreateFontCursor(dpy, XC_bottom_right_corner);
	wPreferences.cursor[WCUR_VERTICALRESIZE] = XCreateFontCursor(dpy, XC_sb_v_double_arrow);
	wPreferences.cursor[WCUR_HORIZONRESIZE] = XCreateFontCursor(dpy, XC_sb_h_double_arrow);
	wPreferences.cursor[WCUR_WAIT] = XCreateFontCursor(dpy, XC_watch);
	wPreferences.cursor[WCUR_QUESTION] = XCreateFontCursor(dpy, XC_question_arrow);
	wPreferences.cursor[WCUR_TEXT] = XCreateFontCursor(dpy, XC_xterm);	/* odd name??? */
	wPreferences.cursor[WCUR_SELECT] = XCreateFontCursor(dpy, XC_cross);

	Pixmap cur = XCreatePixmap(dpy, DefaultRootWindow(dpy), 16, 16, 1);
	GC gc = XCreateGC(dpy, cur, 0, NULL);
	XColor black;
	memset(&black, 0, sizeof(XColor));
	XSetForeground(dpy, gc, 0);
	XFillRectangle(dpy, cur, gc, 0, 0, 16, 16);
	XFreeGC(dpy, gc);
	wPreferences.cursor[WCUR_EMPTY] = XCreatePixmapCursor(dpy, cur, cur, &black, &black, 0, 0);
	XFreePixmap(dpy, cur);

	/* emergency exit... */
	sig_action.sa_handler = handleSig;
	sigemptyset(&sig_action.sa_mask);

	sig_action.sa_flags = SA_RESTART;
	sigaction(SIGQUIT, &sig_action, NULL);
	/* instead of catching these, we let the default handler abort the
	 * program. The new monitor process will take appropriate action
	 * when it detects the crash.
	 sigaction(SIGSEGV, &sig_action, NULL);
	 sigaction(SIGBUS, &sig_action, NULL);
	 sigaction(SIGFPE, &sig_action, NULL);
	 sigaction(SIGABRT, &sig_action, NULL);
	 */

	sig_action.sa_handler = handleExitSig;

	/* Here we set SA_RESTART for safety, because SIGUSR1 may not be handled
	 * immediately. -Dan */
	sig_action.sa_flags = SA_RESTART;
	sigaction(SIGTERM, &sig_action, NULL);
	sigaction(SIGINT, &sig_action, NULL);
	sigaction(SIGHUP, &sig_action, NULL);
	sigaction(SIGUSR1, &sig_action, NULL);
	sigaction(SIGUSR2, &sig_action, NULL);

	/* ignore dead pipe */
	/* Because POSIX mandates that only signal with handlers are reset
	 * accross an exec*(), we do not want to propagate ignoring SIGPIPEs
	 * to children. Hence the dummy handler.
	 * Philippe Troin <*****@*****.**>
	 */
	sig_action.sa_handler = &dummyHandler;
	sig_action.sa_flags = SA_RESTART;
	sigaction(SIGPIPE, &sig_action, NULL);

	/* handle dead children */
	sig_action.sa_handler = buryChild;
	sig_action.sa_flags = SA_NOCLDSTOP | SA_RESTART;
	sigaction(SIGCHLD, &sig_action, NULL);

	/* Now we unblock all signals, that may have been blocked by the parent
	 * who exec()-ed us. This can happen for example if Window Maker crashes
	 * and restarts itself or another window manager from the signal handler.
	 * In this case, the new proccess inherits the blocked signal mask and
	 * will no longer react to that signal, until unblocked.
	 * This is because the signal handler of the proccess who crashed (parent)
	 * didn't return, and the signal remained blocked. -Dan
	 */
	sigfillset(&sig_action.sa_mask);
	sigprocmask(SIG_UNBLOCK, &sig_action.sa_mask, NULL);

	/* handle X shutdowns a such */
	XSetIOErrorHandler(handleXIO);

	/* set hook for out event dispatcher in WINGs event dispatcher */
	WMHookEventHandler(DispatchEvent);

	/* initialize defaults stuff */
	w_global.domain.wmaker = wDefaultsInitDomain("WindowMaker", True);
	if (!w_global.domain.wmaker->dictionary)
		wwarning(_("could not read domain \"%s\" from defaults database"), "WindowMaker");

	/* read defaults that don't change until a restart and are
	 * screen independent */
	wReadStaticDefaults(w_global.domain.wmaker ? w_global.domain.wmaker->dictionary : NULL);

	/* check sanity of some values */
	if (wPreferences.icon_size < 16) {
		wwarning(_("icon size is configured to %i, but it's too small. Using 16 instead"),
			 wPreferences.icon_size);
		wPreferences.icon_size = 16;
	}

	/* init other domains */
	w_global.domain.root_menu = wDefaultsInitDomain("WMRootMenu", False);
	if (!w_global.domain.root_menu->dictionary)
		wwarning(_("could not read domain \"%s\" from defaults database"), "WMRootMenu");

	wDefaultsMergeGlobalMenus(w_global.domain.root_menu);

	w_global.domain.window_attr = wDefaultsInitDomain("WMWindowAttributes", True);
	if (!w_global.domain.window_attr->dictionary)
		wwarning(_("could not read domain \"%s\" from defaults database"), "WMWindowAttributes");

	XSetErrorHandler((XErrorHandler) catchXError);

#ifdef USE_XSHAPE
	/* ignore j */
	w_global.xext.shape.supported = XShapeQueryExtension(dpy, &w_global.xext.shape.event_base, &j);
#endif

#ifdef USE_XRANDR
	w_global.xext.randr.supported = XRRQueryExtension(dpy, &w_global.xext.randr.event_base, &j);
#endif

#ifdef KEEP_XKB_LOCK_STATUS
	w_global.xext.xkb.supported = XkbQueryExtension(dpy, NULL, &w_global.xext.xkb.event_base, NULL, NULL, NULL);
	if (wPreferences.modelock && !w_global.xext.xkb.supported) {
		wwarning(_("XKB is not supported. KbdModeLock is automatically disabled."));
		wPreferences.modelock = 0;
	}
#endif

	if (defaultScreenOnly)
		max = 1;
	else
		max = ScreenCount(dpy);

	wScreen = wmalloc(sizeof(WScreen *) * max);

	w_global.screen_count = 0;

	/* Check if TIFF images are supported */
	formats = RSupportedFileFormats();
	if (formats) {
		for (i = 0; formats[i] != NULL; i++) {
			if (strcmp(formats[i], "TIFF") == 0) {
				wPreferences.supports_tiff = 1;
				break;
			}
		}
	}

	/* manage the screens */
	for (j = 0; j < max; j++) {
		if (defaultScreenOnly || max == 1) {
			wScreen[w_global.screen_count] = wScreenInit(DefaultScreen(dpy));
			if (!wScreen[w_global.screen_count]) {
				wfatal(_("it seems that there is already a window manager running"));
				Exit(1);
			}
		} else {
			wScreen[w_global.screen_count] = wScreenInit(j);
			if (!wScreen[w_global.screen_count]) {
				wwarning(_("could not manage screen %i"), j);
				continue;
			}
		}
		w_global.screen_count++;
	}

	InitializeSwitchMenu();

	/* initialize/restore state for the screens */
	for (j = 0; j < w_global.screen_count; j++) {
		int lastDesktop;

		lastDesktop = wNETWMGetCurrentDesktopFromHint(wScreen[j]);

		wScreenRestoreState(wScreen[j]);

		/* manage all windows that were already here before us */
		if (!wPreferences.flags.nodock && wScreen[j]->dock)
			wScreen[j]->last_dock = wScreen[j]->dock;

		manageAllWindows(wScreen[j], wPreferences.flags.restarting == 2);

		/* restore saved menus */
		wMenuRestoreState(wScreen[j]);

		/* If we're not restarting, restore session */
		if (wPreferences.flags.restarting == 0 && !wPreferences.flags.norestore)
			wSessionRestoreState(wScreen[j]);

		if (!wPreferences.flags.noautolaunch) {
			/* auto-launch apps */
			if (!wPreferences.flags.nodock && wScreen[j]->dock) {
				wScreen[j]->last_dock = wScreen[j]->dock;
				wDockDoAutoLaunch(wScreen[j]->dock, 0);
			}
			/* auto-launch apps in clip */
			if (!wPreferences.flags.noclip) {
				int i;
				for (i = 0; i < w_global.workspace.count; i++) {
					if (w_global.workspace.array[i]->clip) {
						wScreen[j]->last_dock = w_global.workspace.array[i]->clip;
						wDockDoAutoLaunch(w_global.workspace.array[i]->clip, i);
					}
				}
			}
			/* auto-launch apps in drawers */
			if (!wPreferences.flags.nodrawer) {
				WDrawerChain *dc;
				for (dc = wScreen[j]->drawers; dc; dc = dc->next) {
					wScreen[j]->last_dock = dc->adrawer;
					wDockDoAutoLaunch(dc->adrawer, 0);
				}
			}
		}

		/* go to workspace where we were before restart */
		if (lastDesktop >= 0)
			wWorkspaceForceChange(wScreen[j], lastDesktop);
		else
			wSessionRestoreLastWorkspace(wScreen[j]);
	}

	if (w_global.screen_count == 0) {
		wfatal(_("could not manage any screen"));
		Exit(1);
	}

#ifndef HAVE_INOTIFY
	/* setup defaults file polling */
	if (!wPreferences.flags.nopolling && !wPreferences.flags.noupdates)
		WMAddTimerHandler(3000, wDefaultsCheckDomains, NULL);
#endif

}
Esempio n. 12
0
File: start.c Progetto: MSahl/lxc
struct lxc_handler *lxc_init(const char *name, struct lxc_conf *conf, const char *lxcpath)
{
	int i;
	struct lxc_handler *handler;

	handler = malloc(sizeof(*handler));
	if (!handler)
		return NULL;

	memset(handler, 0, sizeof(*handler));

	handler->ttysock[0] = handler->ttysock[1] = -1;
	handler->conf = conf;
	handler->lxcpath = lxcpath;
	handler->pinfd = -1;

	for (i = 0; i < LXC_NS_MAX; i++)
		handler->nsfd[i] = -1;

	lsm_init();

	handler->name = strdup(name);
	if (!handler->name) {
		ERROR("failed to allocate memory");
		goto out_free;
	}

	if (lxc_cmd_init(name, handler, lxcpath))
		goto out_free_name;

	if (lxc_read_seccomp_config(conf) != 0) {
		ERROR("failed loading seccomp policy");
		goto out_close_maincmd_fd;
	}

	/* Begin by setting the state to STARTING */
	if (lxc_set_state(name, handler, STARTING)) {
		ERROR("failed to set state '%s'", lxc_state2str(STARTING));
		goto out_close_maincmd_fd;
	}

	/* Start of environment variable setup for hooks */
	if (name && setenv("LXC_NAME", name, 1)) {
		SYSERROR("failed to set environment variable for container name");
	}
	if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
		SYSERROR("failed to set environment variable for config path");
	}
	if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
		SYSERROR("failed to set environment variable for rootfs mount");
	}
	if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
		SYSERROR("failed to set environment variable for rootfs mount");
	}
	if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1)) {
		SYSERROR("failed to set environment variable for console path");
	}
	if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1)) {
		SYSERROR("failed to set environment variable for console log");
	}
	if (setenv("LXC_CGNS_AWARE", "1", 1)) {
		SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
	}
	/* End of environment variable setup for hooks */

	if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
		ERROR("failed to run pre-start hooks for container '%s'.", name);
		goto out_aborting;
	}

	/* the signal fd has to be created before forking otherwise
	 * if the child process exits before we setup the signal fd,
	 * the event will be lost and the command will be stuck */
	handler->sigfd = setup_signal_fd(&handler->oldmask);
	if (handler->sigfd < 0) {
		ERROR("failed to set sigchild fd handler");
		goto out_delete_tty;
	}

	/* do this after setting up signals since it might unblock SIGWINCH */
	if (lxc_console_create(conf)) {
		ERROR("failed to create console");
		goto out_restore_sigmask;
	}

	if (ttys_shift_ids(conf) < 0) {
		ERROR("Failed to shift tty into container");
		goto out_restore_sigmask;
	}

	INFO("'%s' is initialized", name);
	return handler;

out_restore_sigmask:
	sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
out_delete_tty:
	lxc_delete_tty(&conf->tty_info);
out_aborting:
	lxc_set_state(name, handler, ABORTING);
out_close_maincmd_fd:
	close(conf->maincmd_fd);
	conf->maincmd_fd = -1;
out_free_name:
	free(handler->name);
	handler->name = NULL;
out_free:
	free(handler);
	return NULL;
}
Esempio n. 13
0
static void restore_sigs(sigset_t *oldset)
{
	sigprocmask(SIG_SETMASK, oldset, NULL);
}
Esempio n. 14
0
File: tap.c Progetto: djs55/qemu
static int recv_fd(int c)
{
    int fd;
    uint8_t msgbuf[CMSG_SPACE(sizeof(fd))];
    struct msghdr msg = {
        .msg_control = msgbuf,
        .msg_controllen = sizeof(msgbuf),
    };
    struct cmsghdr *cmsg;
    struct iovec iov;
    uint8_t req[1];
    ssize_t len;

    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
    msg.msg_controllen = cmsg->cmsg_len;

    iov.iov_base = req;
    iov.iov_len = sizeof(req);

    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    len = recvmsg(c, &msg, 0);
    if (len > 0) {
        memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
        return fd;
    }

    return len;
}

static int net_bridge_run_helper(const char *helper, const char *bridge)
{
    sigset_t oldmask, mask;
    int pid, status;
    char *args[5];
    char **parg;
    int sv[2];

    sigemptyset(&mask);
    sigaddset(&mask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &mask, &oldmask);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        return -1;
    }

    /* try to launch bridge helper */
    pid = fork();
    if (pid == 0) {
        int open_max = sysconf(_SC_OPEN_MAX), i;
        char fd_buf[6+10];
        char br_buf[6+IFNAMSIZ] = {0};
        char helper_cmd[PATH_MAX + sizeof(fd_buf) + sizeof(br_buf) + 15];

        for (i = 0; i < open_max; i++) {
            if (i != STDIN_FILENO &&
                i != STDOUT_FILENO &&
                i != STDERR_FILENO &&
                i != sv[1]) {
                close(i);
            }
        }

        snprintf(fd_buf, sizeof(fd_buf), "%s%d", "--fd=", sv[1]);

        if (strrchr(helper, ' ') || strrchr(helper, '\t')) {
            /* assume helper is a command */

            if (strstr(helper, "--br=") == NULL) {
                snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);
            }

            snprintf(helper_cmd, sizeof(helper_cmd), "%s %s %s %s",
                     helper, "--use-vnet", fd_buf, br_buf);

            parg = args;
            *parg++ = (char *)"sh";
            *parg++ = (char *)"-c";
            *parg++ = helper_cmd;
            *parg++ = NULL;

            execv("/bin/sh", args);
        } else {
            /* assume helper is just the executable path name */

            snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);

            parg = args;
            *parg++ = (char *)helper;
            *parg++ = (char *)"--use-vnet";
            *parg++ = fd_buf;
            *parg++ = br_buf;
            *parg++ = NULL;

            execv(helper, args);
        }
        _exit(1);

    } else if (pid > 0) {
        int fd;

        close(sv[1]);

        do {
            fd = recv_fd(sv[0]);
        } while (fd == -1 && errno == EINTR);

        close(sv[0]);

        while (waitpid(pid, &status, 0) != pid) {
            /* loop */
        }
        sigprocmask(SIG_SETMASK, &oldmask, NULL);
        if (fd < 0) {
            fprintf(stderr, "failed to recv file descriptor\n");
            return -1;
        }

        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
            return fd;
        }
    }
    fprintf(stderr, "failed to launch bridge helper\n");
    return -1;
}
Esempio n. 15
0
static RETSIGTYPE
info_signal_proc (int sig)
{
  signal_info *old_signal_handler = NULL;

#if !defined (HAVE_SIGACTION)
  /* best effort: first increment this counter and later block signals */
  if (term_conf_busy)
    return;
  term_conf_busy++;
#if defined (HAVE_SIGPROCMASK) || defined (HAVE_SIGSETMASK)
    {
      sigset_t nvar, ovar;
      sigemptyset (&nvar);
      mask_termsig (&nvar);
      sigprocmask (SIG_BLOCK, &nvar, &ovar);
    }
#endif /* HAVE_SIGPROCMASK || HAVE_SIGSETMASK */
#endif /* !HAVE_SIGACTION */
  switch (sig)
    {
#if defined (SIGTSTP)
    case SIGTSTP:
    case SIGTTOU:
    case SIGTTIN:
#endif
#if defined (SIGQUIT)
    case SIGQUIT:
#endif
#if defined (SIGINT)
    case SIGINT:
#endif
#if defined (SIGTERM)
    case SIGTERM:
#endif
      {
#if defined (SIGTSTP)
        if (sig == SIGTSTP)
          old_signal_handler = &old_TSTP;
        if (sig == SIGTTOU)
          old_signal_handler = &old_TTOU;
        if (sig == SIGTTIN)
          old_signal_handler = &old_TTIN;
#endif /* SIGTSTP */
#if defined (SIGQUIT)
        if (sig == SIGQUIT)
          old_signal_handler = &old_QUIT;
#endif /* SIGQUIT */
#if defined (SIGINT)
        if (sig == SIGINT)
          old_signal_handler = &old_INT;
#endif /* SIGINT */
#if defined (SIGTERM)
        if (sig == SIGTERM)
          old_signal_handler = &old_TERM;
#endif /* SIGTERM */

        /* For stop signals, restore the terminal IO, leave the cursor
           at the bottom of the window, and stop us. */
        terminal_goto_xy (0, screenheight - 1);
        terminal_clear_to_eol ();
        fflush (stdout);
        terminal_unprep_terminal ();
	restore_termsig (sig, old_signal_handler);
	UNBLOCK_SIGNAL (sig);
	kill (getpid (), sig);

        /* The program is returning now.  Restore our signal handler,
           turn on terminal handling, redraw the screen, and place the
           cursor where it belongs. */
        terminal_prep_terminal ();
	set_termsig (sig, old_signal_handler);
	/* window size might be changed while sleeping */
	reset_info_window_sizes ();
      }
      break;

#if defined (SIGWINCH) || defined (SIGUSR1)
#ifdef SIGWINCH
    case SIGWINCH:
#endif
#ifdef SIGUSR1
    case SIGUSR1:
#endif
      {
	/* Turn off terminal IO, tell our parent that the window has changed,
	   then reinitialize the terminal and rebuild our windows. */
#ifdef SIGWINCH
	if (sig == SIGWINCH)
	  old_signal_handler = &old_WINCH;
#endif
#ifdef SIGUSR1
	if (sig == SIGUSR1)
	  old_signal_handler = &old_USR1;
#endif

        /* This seems risky: what if we receive a (real) signal before
           the next line is reached? */
#if 0
	restore_termsig (sig, old_signal_handler);
	kill (getpid (), sig);
#endif

	/* After our old signal handler returns... */
	set_termsig (sig, old_signal_handler); /* needless? */

        if (sigwinch_block_count != 0)
          abort ();

        /* Avoid any of the code unblocking the signal too early.  This
           should set the variable to 1 because we shouldn't be here if
           sigwinch_block_count > 0. */
        sigwinch_block_count++;

	reset_info_window_sizes ();

        sigwinch_block_count--;
        /* Don't unblock the signal until after we've finished. */
	UNBLOCK_SIGNAL (sig);
      }
      break;
#endif /* SIGWINCH || SIGUSR1 */
    }
#if !defined (HAVE_SIGACTION)
  /* at this time it is safer to perform unblock after decrement */
  term_conf_busy--;
#if defined (HAVE_SIGPROCMASK) || defined (HAVE_SIGSETMASK)
    {
      sigset_t nvar, ovar;
      sigemptyset (&nvar);
      mask_termsig (&nvar);
      sigprocmask (SIG_UNBLOCK, &nvar, &ovar);
    }
#endif /* HAVE_SIGPROCMASK || HAVE_SIGSETMASK */
#endif /* !HAVE_SIGACTION */
}
Esempio n. 16
0
void signals_unblock()
{
sigprocmask( SIG_UNBLOCK, &g_sigset, NULL );
}
Esempio n. 17
0
void Sigprocmask(int how, const sigset_t *set, sigset_t *oldset)
{
    if (sigprocmask(how, set, oldset) < 0)
	unix_error("Sigprocmask error");
    return;
}
Esempio n. 18
0
File: 3-3.c Progetto: Nan619/ltp-ddt
int main(int argc, char *argv[])
{
	sigset_t set;
	struct sigevent ev;
	struct sigaction act;
	timer_t tid;
	struct itimerspec its;
	struct timespec ts;

	ev.sigev_notify = SIGEV_SIGNAL;
	ev.sigev_signo = SIGTOTEST;

	if (sigemptyset(&set) != 0) {
		perror("sigemptyset() did not return success\n");
		return PTS_UNRESOLVED;
	}

	if (sigaddset(&set, SIGTOTEST) != 0) {
		perror("sigaddset() did not return success\n");
		return PTS_UNRESOLVED;
	}

	if (sigprocmask(SIG_SETMASK, &set, NULL) != 0) {
		perror("sigprocmask() did not return success\n");
		return PTS_UNRESOLVED;
	}

	if (timer_create(CLOCK_REALTIME, &ev, &tid) != 0) {
		perror("timer_create() did not return success\n");
		return PTS_UNRESOLVED;
	}

	/*
	 * First set up timer to be blocked
	 */
	its.it_interval.tv_sec = 0;
	its.it_interval.tv_nsec = 0;
	its.it_value.tv_sec = 0;
	its.it_value.tv_nsec = TIMEREXPIRENSEC;

	printf("setup first timer\n");
	if (timer_settime(tid, 0, &its, NULL) != 0) {
		perror("timer_settime() did not return success\n");
		return PTS_UNRESOLVED;
	}

	printf("sleep\n");
	sleep(SLEEPTIME);
	printf("awoke\n");

	/*
	 * Second, set value.it_value = 0 and set up handler to catch
	 * signal.
	 */
	act.sa_handler = handler;
	act.sa_flags = 0;

	if (sigemptyset(&act.sa_mask) == -1) {
		perror("Error calling sigemptyset\n");
		return PTS_UNRESOLVED;
	}
	if (sigaction(SIGTOTEST, &act, 0) == -1) {
		perror("Error calling sigaction\n");
		return PTS_UNRESOLVED;
	}

	its.it_interval.tv_sec = 0;
	its.it_interval.tv_nsec = 0;
	its.it_value.tv_sec = 0;
	its.it_value.tv_nsec = 0;

	printf("setup second timer\n");
	if (timer_settime(tid, 0, &its, NULL) != 0) {
		perror("timer_settime() did not return success\n");
		return PTS_UNRESOLVED;
	}

	printf("unblock\n");
	if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) {
		perror("sigprocmask() did not return success\n");
		return PTS_UNRESOLVED;
	}

	/*
	 * Ensure sleep for TIMEREXPIRE seconds not interrupted
	 */
	ts.tv_sec = SLEEPTIME;
	ts.tv_nsec = 0;

	printf("sleep again\n");
	if (nanosleep(&ts, NULL) == -1) {
		printf("nanosleep() interrupted\n");
		printf("Test FAILED\n");
		return PTS_FAIL;
	}

	printf("Test PASSED\n");
	return PTS_PASS;
}
Esempio n. 19
0
static void
ngx_worker_process_init(ngx_cycle_t *cycle, ngx_uint_t priority)
{
    sigset_t          set;
    ngx_int_t         n;
    ngx_uint_t        i;
    struct rlimit     rlmt;
    ngx_core_conf_t  *ccf;
    ngx_listening_t  *ls;

    if (ngx_set_environment(cycle, NULL) == NULL) {
        /* fatal */
        exit(2);
    }

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (priority && ccf->priority != 0) {
        if (setpriority(PRIO_PROCESS, 0, ccf->priority) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setpriority(%d) failed", ccf->priority);
        }
    }

    if (ccf->rlimit_nofile != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_nofile;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_nofile;

        if (setrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_NOFILE, %i) failed",
                          ccf->rlimit_nofile);
        }
    }

    if (ccf->rlimit_core != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_core;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_core;

        if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_CORE, %O) failed",
                          ccf->rlimit_core);
        }
    }

#ifdef RLIMIT_SIGPENDING
    if (ccf->rlimit_sigpending != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_sigpending;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_sigpending;

        if (setrlimit(RLIMIT_SIGPENDING, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_SIGPENDING, %i) failed",
                          ccf->rlimit_sigpending);
        }
    }
#endif

    if (geteuid() == 0) {
        if (setgid(ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setgid(%d) failed", ccf->group);
            /* fatal */
            exit(2);
        }

        if (initgroups(ccf->username, ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "initgroups(%s, %d) failed",
                          ccf->username, ccf->group);
        }

        if (setuid(ccf->user) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setuid(%d) failed", ccf->user);
            /* fatal */
            exit(2);
        }
    }

#if (NGX_HAVE_SCHED_SETAFFINITY)

    if (cpu_affinity) {
        ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0,
                      "sched_setaffinity(0x%08Xl)", cpu_affinity);

        if (sched_setaffinity(0, 32, (cpu_set_t *) &cpu_affinity) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "sched_setaffinity(0x%08Xl) failed", cpu_affinity);
        }
    }

#endif

#if (NGX_HAVE_PR_SET_DUMPABLE)

    /* allow coredump after setuid() in Linux 2.4.x */

    if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "prctl(PR_SET_DUMPABLE) failed");
    }

#endif

    if (ccf->working_directory.len) {
        if (chdir((char *) ccf->working_directory.data) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "chdir(\"%s\") failed", ccf->working_directory.data);
            /* fatal */
            exit(2);
        }
    }

    sigemptyset(&set);

    if (sigprocmask(SIG_SETMASK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    /*
     * disable deleting previous events for the listening sockets because
     * in the worker processes there are no events at all at this point
     */
    ls = cycle->listening.elts;
    for (i = 0; i < cycle->listening.nelts; i++) {
        ls[i].previous = NULL;
    }

    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->init_process) {
            if (ngx_modules[i]->init_process(cycle) == NGX_ERROR) {
                /* fatal */
                exit(2);
            }
        }
    }

    for (n = 0; n < ngx_last_process; n++) {

        if (ngx_processes[n].pid == -1) {
            continue;
        }

        if (n == ngx_process_slot) {
            continue;
        }

        if (ngx_processes[n].channel[1] == -1) {
            continue;
        }

        if (close(ngx_processes[n].channel[1]) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "close() channel failed");
        }
    }

    if (close(ngx_processes[ngx_process_slot].channel[0]) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "close() channel failed");
    }

#if 0
    ngx_last_process = 0;
#endif

    if (ngx_add_channel_event(cycle, ngx_channel, NGX_READ_EVENT,
                              ngx_channel_handler)
        == NGX_ERROR)
    {
        /* fatal */
        exit(2);
    }
}
Esempio n. 20
0
/* Open a pipe connected to a child process.
 *
 *           write       system                read
 *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child       if pipe_stdin
 *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child       if pipe_stdout
 *           read        system                write
 *
 * At least one of pipe_stdin, pipe_stdout must be true.
 * pipe_stdin and prog_stdin together determine the child's standard input.
 * pipe_stdout and prog_stdout together determine the child's standard output.
 * If pipe_stdin is true, prog_stdin is ignored.
 * If pipe_stdout is true, prog_stdout is ignored.
 */
static pid_t
create_pipe (const char *progname,
             const char *prog_path, char **prog_argv,
             bool pipe_stdin, bool pipe_stdout,
             const char *prog_stdin, const char *prog_stdout,
             bool null_stderr,
             bool slave_process, bool exit_on_error,
             int fd[2])
{
#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ || defined __KLIBC__

  /* Native Windows API.
     This uses _pipe(), dup2(), and spawnv().  It could also be implemented
     using the low-level functions CreatePipe(), DuplicateHandle(),
     CreateProcess() and _open_osfhandle(); see the GNU make and GNU clisp
     and cvs source code.  */
  int ifd[2];
  int ofd[2];
  int orig_stdin;
  int orig_stdout;
  int orig_stderr;
  int child;
  int nulloutfd;
  int stdinfd;
  int stdoutfd;
  int saved_errno;

  /* FIXME: Need to free memory allocated by prepare_spawn.  */
  prog_argv = prepare_spawn (prog_argv);

  if (pipe_stdout)
    if (pipe2_safer (ifd, O_BINARY | O_CLOEXEC) < 0)
      error (EXIT_FAILURE, errno, _("cannot create pipe"));
  if (pipe_stdin)
    if (pipe2_safer (ofd, O_BINARY | O_CLOEXEC) < 0)
      error (EXIT_FAILURE, errno, _("cannot create pipe"));
/* Data flow diagram:
 *
 *           write        system         read
 *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
 *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
 *           read         system         write
 *
 */

  /* Save standard file handles of parent process.  */
  if (pipe_stdin || prog_stdin != NULL)
    orig_stdin = dup_safer_noinherit (STDIN_FILENO);
  if (pipe_stdout || prog_stdout != NULL)
    orig_stdout = dup_safer_noinherit (STDOUT_FILENO);
  if (null_stderr)
    orig_stderr = dup_safer_noinherit (STDERR_FILENO);
  child = -1;

  /* Create standard file handles of child process.  */
  nulloutfd = -1;
  stdinfd = -1;
  stdoutfd = -1;
  if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
      && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
      && (!null_stderr
          || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
              && (nulloutfd == STDERR_FILENO
                  || (dup2 (nulloutfd, STDERR_FILENO) >= 0
                      && close (nulloutfd) >= 0))))
      && (pipe_stdin
          || prog_stdin == NULL
          || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
              && (stdinfd == STDIN_FILENO
                  || (dup2 (stdinfd, STDIN_FILENO) >= 0
                      && close (stdinfd) >= 0))))
      && (pipe_stdout
          || prog_stdout == NULL
          || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
              && (stdoutfd == STDOUT_FILENO
                  || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
                      && close (stdoutfd) >= 0)))))
    /* The child process doesn't inherit ifd[0], ifd[1], ofd[0], ofd[1],
       but it inherits all open()ed or dup2()ed file handles (which is what
       we want in the case of STD*_FILENO).  */
    /* Use spawnvpe and pass the environment explicitly.  This is needed if
       the program has modified the environment using putenv() or [un]setenv().
       On Windows, programs have two environments, one in the "environment
       block" of the process and managed through SetEnvironmentVariable(), and
       one inside the process, in the location retrieved by the 'environ'
       macro.  When using spawnvp() without 'e', the child process inherits a
       copy of the environment block - ignoring the effects of putenv() and
       [un]setenv().  */
    {
      child = spawnvpe (P_NOWAIT, prog_path, (const char **) prog_argv,
                        (const char **) environ);
      if (child < 0 && errno == ENOEXEC)
        {
          /* prog is not a native executable.  Try to execute it as a
             shell script.  Note that prepare_spawn() has already prepended
             a hidden element "sh.exe" to prog_argv.  */
          --prog_argv;
          child = spawnvpe (P_NOWAIT, prog_argv[0], (const char **) prog_argv,
                            (const char **) environ);
        }
    }
  if (child == -1)
    saved_errno = errno;
  if (stdinfd >= 0)
    close (stdinfd);
  if (stdoutfd >= 0)
    close (stdoutfd);
  if (nulloutfd >= 0)
    close (nulloutfd);

  /* Restore standard file handles of parent process.  */
  if (null_stderr)
    undup_safer_noinherit (orig_stderr, STDERR_FILENO);
  if (pipe_stdout || prog_stdout != NULL)
    undup_safer_noinherit (orig_stdout, STDOUT_FILENO);
  if (pipe_stdin || prog_stdin != NULL)
    undup_safer_noinherit (orig_stdin, STDIN_FILENO);

  if (pipe_stdin)
    close (ofd[0]);
  if (pipe_stdout)
    close (ifd[1]);
  if (child == -1)
    {
      if (exit_on_error || !null_stderr)
        error (exit_on_error ? EXIT_FAILURE : 0, saved_errno,
               _("%s subprocess failed"), progname);
      if (pipe_stdout)
        close (ifd[0]);
      if (pipe_stdin)
        close (ofd[1]);
      errno = saved_errno;
      return -1;
    }

  if (pipe_stdout)
    fd[0] = ifd[0];
  if (pipe_stdin)
    fd[1] = ofd[1];
  return child;

#else

  /* Unix API.  */
  int ifd[2];
  int ofd[2];
  sigset_t blocked_signals;
  posix_spawn_file_actions_t actions;
  bool actions_allocated;
  posix_spawnattr_t attrs;
  bool attrs_allocated;
  int err;
  pid_t child;

  if (pipe_stdout)
    if (pipe_safer (ifd) < 0)
      error (EXIT_FAILURE, errno, _("cannot create pipe"));
  if (pipe_stdin)
    if (pipe_safer (ofd) < 0)
      error (EXIT_FAILURE, errno, _("cannot create pipe"));
/* Data flow diagram:
 *
 *           write        system         read
 *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
 *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
 *           read         system         write
 *
 */

  if (slave_process)
    {
      sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
      block_fatal_signals ();
    }
  actions_allocated = false;
  attrs_allocated = false;
  if ((err = posix_spawn_file_actions_init (&actions)) != 0
      || (actions_allocated = true,
          (pipe_stdin
           && (err = posix_spawn_file_actions_adddup2 (&actions,
                                                       ofd[0], STDIN_FILENO))
              != 0)
          || (pipe_stdout
              && (err = posix_spawn_file_actions_adddup2 (&actions,
                                                          ifd[1], STDOUT_FILENO))
                 != 0)
          || (pipe_stdin
              && (err = posix_spawn_file_actions_addclose (&actions, ofd[0]))
                 != 0)
          || (pipe_stdout
              && (err = posix_spawn_file_actions_addclose (&actions, ifd[1]))
                 != 0)
          || (pipe_stdin
              && (err = posix_spawn_file_actions_addclose (&actions, ofd[1]))
                 != 0)
          || (pipe_stdout
              && (err = posix_spawn_file_actions_addclose (&actions, ifd[0]))
                 != 0)
          || (null_stderr
              && (err = posix_spawn_file_actions_addopen (&actions,
                                                          STDERR_FILENO,
                                                          "/dev/null", O_RDWR,
                                                          0))
                 != 0)
          || (!pipe_stdin
              && prog_stdin != NULL
              && (err = posix_spawn_file_actions_addopen (&actions,
                                                          STDIN_FILENO,
                                                          prog_stdin, O_RDONLY,
                                                          0))
                 != 0)
          || (!pipe_stdout
              && prog_stdout != NULL
              && (err = posix_spawn_file_actions_addopen (&actions,
                                                          STDOUT_FILENO,
                                                          prog_stdout, O_WRONLY,
                                                          0))
                 != 0)
          || (slave_process
              && ((err = posix_spawnattr_init (&attrs)) != 0
                  || (attrs_allocated = true,
                      (err = posix_spawnattr_setsigmask (&attrs,
                                                         &blocked_signals))
                      != 0
                      || (err = posix_spawnattr_setflags (&attrs,
                                                        POSIX_SPAWN_SETSIGMASK))
                         != 0)))
          || (err = posix_spawnp (&child, prog_path, &actions,
                                  attrs_allocated ? &attrs : NULL, prog_argv,
                                  environ))
             != 0))
    {
      if (actions_allocated)
        posix_spawn_file_actions_destroy (&actions);
      if (attrs_allocated)
        posix_spawnattr_destroy (&attrs);
      if (slave_process)
        unblock_fatal_signals ();
      if (exit_on_error || !null_stderr)
        error (exit_on_error ? EXIT_FAILURE : 0, err,
               _("%s subprocess failed"), progname);
      if (pipe_stdout)
        {
          close (ifd[0]);
          close (ifd[1]);
        }
      if (pipe_stdin)
        {
          close (ofd[0]);
          close (ofd[1]);
        }
      errno = err;
      return -1;
    }
  posix_spawn_file_actions_destroy (&actions);
  if (attrs_allocated)
    posix_spawnattr_destroy (&attrs);
  if (slave_process)
    {
      register_slave_subprocess (child);
      unblock_fatal_signals ();
    }
  if (pipe_stdin)
    close (ofd[0]);
  if (pipe_stdout)
    close (ifd[1]);

  if (pipe_stdout)
    fd[0] = ifd[0];
  if (pipe_stdin)
    fd[1] = ofd[1];
  return child;

#endif
}
Esempio n. 21
0
int main(int argc, char **argv)
{	
	clock_t tic = clock();
	FILE *fp; 
	int i, choice, err;
	long numBytes;
	long Inpt= 0;
	int rem = 0;
	pid_t pid[NUM_THR_PROC];
	struct primeArr *primeArray;
	int object_size = 1024 * 1024 * 600;
	sigset_t blockMask, origMask;
    struct sigaction saIgnore, saOrigQuit, saOrigInt, saDefault;
	
	printf("Please enter the max integer to search through for primes: ---->    ");
	scanf("%ld",&Inpt);
//	derp(Inpt);



//	Used this function to initially get my numbers into a BITMAP
//	primeArray = crinit_primeArr(Inpt);
//	IgnorePts(primeArray);
//	p_primeArr(primeArray);						//<<<-------------------------
//	mapPrimes(primeArray->num, Inpt);
//	freeArr(primeArray);

	
	//The number of bytes we want to pull in 
	
	numBytes = Inpt / 4; 							//4 numbers are kept per char.
//	printf("ERROR\n");
	if (Inpt % 4 > 0) { numBytes++;}
//	printf("ERROR\n");
	unsigned char *myPrimes = malloc(sizeof(unsigned char*) * numBytes);
	//char myPrimes[numBytes];						//So we get an array of that many chars(x4 numbers)
//	printf("ERRORhelp\n");
	
	//We open our bitmap(hashed in chars) and set it in the global list array
	fp = fopen("bitMap", "r");
	fread(List, sizeof(myPrimes[0]), numBytes, fp );
	//printf("ERROR\n");	
	Inpt = numBytes / NUM_THR_PROC;
	rem = numBytes % NUM_THR_PROC;

	printf("Would you like to run threads or system? 1 for threads, 2 for system, anything else to quit");
	scanf("%d",&choice); 
	
	//SIGNAL DEALING
	
	sigemptyset(&blockMask);            /* Block SIGCHLD */
    sigaddset(&blockMask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &blockMask, &origMask);

    saIgnore.sa_handler = SIG_IGN;      /* Ignore SIGINT and SIGQUIT */
    saIgnore.sa_flags = 0;
    sigemptyset(&saIgnore.sa_mask);
    sigaction(SIGINT, &saIgnore, &saOrigInt);
    sigaction(SIGQUIT, &saIgnore, &saOrigQuit);
	if(choice == 1)
		runThreads(numBytes, Inpt, rem);
		
	if(choice == 2)
	{
		void *myAddr = mount_shmem("/shProc", object_size);
		myAddr = List;
		
		for(i = 0; i < NUM_THR_PROC; i++)
		{
			for(i=0; i<NUM_THR_PROC; ++i)
			{
				d[i].Depth = numBytes;
				int j = 0;
				int k = 0;
				d[i].offset = i;
				d[i].sliceSt = (Inpt * i);										
				d[i].sliceEnd = Inpt * (i + 1);
				
				//If it is our last fork or thread...
				if(i == NUM_THR_PROC - 1)
				{
					d[i].sliceEnd = d[i].sliceEnd + rem;
				}
			}
		}
		for(i = 0; i < NUM_THR_PROC; i++)
		{		
			switch(pid[i] = fork())
			{
				case -1:
					fprintf(stderr, "Fork failed");
				case 0: //child process
					saDefault.sa_handler = SIG_DFL;
					saDefault.sa_flags = 0;
					sigemptyset(&saDefault.sa_mask);

					if (saOrigInt.sa_handler != SIG_IGN)
						sigaction(SIGINT, &saDefault, NULL);
					if (saOrigQuit.sa_handler != SIG_IGN)
						sigaction(SIGQUIT, &saDefault, NULL);

					sigprocmask(SIG_SETMASK, &origMask, NULL);
					printf("%d start: \n", d[i].sliceSt);
					printf("%d end: \n", d->sliceEnd);
					runSystem(d[i].sliceSt, d[i].sliceEnd, d[i].offset);
					
					exit(EXIT_SUCCESS);
				default:
					break;
			}
		}
		
	}

	//Parse the char array and extract all happy primes with this FUNCtion.
	mapTurnin(numBytes);
	
	while(wait(NULL) != -1);
    shm_unlink("/shProc");
	

	clock_t toc = clock();

    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
	return EXIT_SUCCESS;
}
Esempio n. 22
0
int
main(int argc, char *argv[])
{
	struct tm local;
	struct timeval tv, *stv;
	struct timezone tz, *stz;
	int kern_offset, wall_clock, disrtcset;
	size_t len;
	/* Avoid time_t here, can be unsigned long or worse */
	long offset, localsec, diff;
	time_t initial_sec, final_sec;
	int ch;
	int initial_isdst = -1, final_isdst;
	int need_restore = False, sleep_mode = False, looping,
	    init = Unknown;
	sigset_t mask, emask;

	while ((ch = getopt(argc, argv, "ais")) != -1)
		switch((char)ch) {
		case 'i':               /* initial call, save offset */
			if (init != Unknown)
				usage();
			init = True;
			break;
		case 'a':               /* adjustment call, use saved offset */
			if (init != Unknown)
				usage();
			init = False;
			break;
		case 's':
			sleep_mode = True;
			break;
		default:
			usage();
		}
	if (init == Unknown)
		usage();

	if (access(_PATH_CLOCK, F_OK) != 0)
		return 0;

	if (init)
		sleep_mode = True;

	sigemptyset(&mask);
	sigemptyset(&emask);
	sigaddset(&mask, SIGTERM);

	openlog("adjkerntz", LOG_PID|LOG_PERROR, LOG_DAEMON);

	(void) signal(SIGHUP, SIG_IGN);

	if (init && daemon(0,
#ifdef DEBUG
	    1
#else
	    0
#endif
	    )) {
		syslog(LOG_ERR, "daemon: %m");
		return 1;
	}

again:
	(void) sigprocmask(SIG_BLOCK, &mask, NULL);
	(void) signal(SIGTERM, fake);

	diff = 0;
	stv = NULL;
	stz = NULL;
	looping = False;

	wall_clock = (access(_PATH_CLOCK, F_OK) == 0);
	if (init && !sleep_mode) {
		init = False;
		if (!wall_clock)
			return 0;
	}

	tzset();

	len = sizeof(kern_offset);
	if (sysctlbyname("machdep.adjkerntz", &kern_offset, &len, NULL, 0) == -1) {
		syslog(LOG_ERR, "sysctl(\"machdep.adjkerntz\"): %m");
		return 1;
	}

/****** Critical section, do all things as fast as possible ******/

	/* get local CMOS clock and possible kernel offset */
	if (gettimeofday(&tv, &tz)) {
		syslog(LOG_ERR, "gettimeofday: %m");
		return 1;
	}

	/* get the actual local timezone difference */
	initial_sec = tv.tv_sec;

recalculate:
	local = *localtime(&initial_sec);
	if (diff == 0)
		initial_isdst = local.tm_isdst;
	local.tm_isdst = initial_isdst;

	/* calculate local CMOS diff from GMT */

	localsec = mktime(&local);
	if (localsec == -1) {
		/*
		 * XXX user can only control local time, and it is
		 * unacceptable to fail here for init.  2:30 am in the
		 * middle of the nonexistent hour means 3:30 am.
		 */
		if (!sleep_mode) {
			syslog(LOG_WARNING,
			"Warning: nonexistent local time, try to run later.");
			syslog(LOG_WARNING, "Giving up.");
			return 1;
		}
		syslog(LOG_WARNING,
			"Warning: nonexistent local time.");
		syslog(LOG_WARNING, "Will retry after %d minutes.",
			REPORT_PERIOD / 60);
		(void) signal(SIGTERM, SIG_DFL);
		(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
		(void) sleep(REPORT_PERIOD);
		goto again;
	}
	offset = -local.tm_gmtoff;
#ifdef DEBUG
	fprintf(stderr, "Initial offset: %ld secs\n", offset);
#endif

	/* correct the kerneltime for this diffs */
	/* subtract kernel offset, if present, old offset too */

	diff = offset - tz.tz_minuteswest * 60 - kern_offset;

	if (diff != 0) {
#ifdef DEBUG
		fprintf(stderr, "Initial diff: %ld secs\n", diff);
#endif
		/* Yet one step for final time */

		final_sec = initial_sec + diff;

		/* get the actual local timezone difference */
		local = *localtime(&final_sec);
		final_isdst = diff < 0 ? initial_isdst : local.tm_isdst;
		if (diff > 0 && initial_isdst != final_isdst) {
			if (looping)
				goto bad_final;
			looping = True;
			initial_isdst = final_isdst;
			goto recalculate;
		}
		local.tm_isdst =  final_isdst;

		localsec = mktime(&local);
		if (localsec == -1) {
		bad_final:
			/*
			 * XXX as above.  The user has even less control,
			 * but perhaps we never get here.
			 */
			if (!sleep_mode) {
				syslog(LOG_WARNING,
					"Warning: nonexistent final local time, try to run later.");
				syslog(LOG_WARNING, "Giving up.");
				return 1;
			}
			syslog(LOG_WARNING,
				"Warning: nonexistent final local time.");
			syslog(LOG_WARNING, "Will retry after %d minutes.",
				REPORT_PERIOD / 60);
			(void) signal(SIGTERM, SIG_DFL);
			(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
			(void) sleep(REPORT_PERIOD);
			goto again;
		}
		offset = -local.tm_gmtoff;
#ifdef DEBUG
		fprintf(stderr, "Final offset: %ld secs\n", offset);
#endif

		/* correct the kerneltime for this diffs */
		/* subtract kernel offset, if present, old offset too */

		diff = offset - tz.tz_minuteswest * 60 - kern_offset;

		if (diff != 0) {
#ifdef DEBUG
			fprintf(stderr, "Final diff: %ld secs\n", diff);
#endif
			/*
			 * stv is abused as a flag.  The important value
			 * is in `diff'.
			 */
			stv = &tv;
		}
	}

	if (tz.tz_dsttime != 0 || tz.tz_minuteswest != 0) {
		tz.tz_dsttime = tz.tz_minuteswest = 0;  /* zone info is garbage */
		stz = &tz;
	}
	if (!wall_clock && stz == NULL)
		stv = NULL;

	/* if init or UTC clock and offset/date will be changed, */
	/* disable RTC modification for a while.                      */

	if (   (init && stv != NULL)
	    || ((init || !wall_clock) && kern_offset != offset)
	   ) {
		len = sizeof(disrtcset);
		if (sysctlbyname("machdep.disable_rtc_set", &disrtcset, &len, NULL, 0) == -1) {
			syslog(LOG_ERR, "sysctl(get: \"machdep.disable_rtc_set\"): %m");
			return 1;
		}
		if (disrtcset == 0) {
			disrtcset = 1;
			need_restore = True;
			if (sysctlbyname("machdep.disable_rtc_set", NULL, NULL, &disrtcset, len) == -1) {
				syslog(LOG_ERR, "sysctl(set: \"machdep.disable_rtc_set\"): %m");
				return 1;
			}
		}
	}

	if (   (init && (stv != NULL || stz != NULL))
	    || (stz != NULL && stv == NULL)
	   ) {
		if (stv != NULL) {
			/*
			 * Get the time again, as close as possible to
			 * adjusting it, to minimise drift.
			 * XXX we'd better not fail between here and
			 * restoring disrtcset, since we don't clean up
			 * anything.
			 */
			(void)gettimeofday(&tv, NULL);
			tv.tv_sec += diff;
			stv = &tv;
		}
		if (settimeofday(stv, stz)) {
			syslog(LOG_ERR, "settimeofday: %m");
			return 1;
		}
	}

	/* setting machdep.adjkerntz have a side effect: resettodr(), which */
	/* can be disabled by machdep.disable_rtc_set, so if init or UTC clock    */
	/* -- don't write RTC, else write RTC.                          */

	if (kern_offset != offset) {
		kern_offset = offset;
		len = sizeof(kern_offset);
		if (sysctlbyname("machdep.adjkerntz", NULL, NULL, &kern_offset, len) == -1) {
			syslog(LOG_ERR, "sysctl(set: \"machdep.adjkerntz\"): %m");
			return 1;
		}
	}

	len = sizeof(wall_clock);
	if (sysctlbyname("machdep.wall_cmos_clock",  NULL, NULL, &wall_clock, len) == -1) {
		syslog(LOG_ERR, "sysctl(set: \"machdep.wall_cmos_clock\"): %m");
		return 1;
	}

	if (need_restore) {
		need_restore = False;
		disrtcset = 0;
		len = sizeof(disrtcset);
		if (sysctlbyname("machdep.disable_rtc_set", NULL, NULL, &disrtcset, len) == -1) {
			syslog(LOG_ERR, "sysctl(set: \"machdep.disable_rtc_set\"): %m");
			return 1;
		}
	}

/****** End of critical section ******/

	if (init && wall_clock) {
		sleep_mode = False;
		/* wait for signals and acts like -a */
		(void) sigsuspend(&emask);
		goto again;
	}

	return 0;
}
Esempio n. 23
0
static gboolean
sendmail_send_to_sync (CamelTransport *transport,
                       CamelMimeMessage *message,
                       CamelAddress *from,
                       CamelAddress *recipients,
		       gboolean *out_sent_message_saved,
                       GCancellable *cancellable,
                       GError **error)
{
	CamelNameValueArray *previous_headers = NULL;
	const gchar *header_name = NULL, *header_value = NULL;
	const gchar *from_addr, *addr;
	GPtrArray *argv_arr;
	gint i, len, fd[2], nullfd, wstat;
	CamelStream *filter;
	CamelMimeFilter *crlf;
	sigset_t mask, omask;
	CamelStream *out;
	CamelSendmailSettings *settings;
	const gchar *binary = SENDMAIL_PATH;
	gchar *custom_binary = NULL, *custom_args = NULL;
	gboolean success;
	pid_t pid;
	guint ii;

	success = camel_internet_address_get (
		CAMEL_INTERNET_ADDRESS (from), 0, NULL, &from_addr);

	if (!success) {
		g_set_error (
			error, CAMEL_ERROR, CAMEL_ERROR_GENERIC,
			_("Failed to read From address"));
		return FALSE;
	}

	settings = CAMEL_SENDMAIL_SETTINGS (camel_service_ref_settings (CAMEL_SERVICE (transport)));

	if (!camel_sendmail_settings_get_send_in_offline (settings)) {
		CamelSession *session;
		gboolean is_online;

		session = camel_service_ref_session (CAMEL_SERVICE (transport));
		is_online = session && camel_session_get_online (session);
		g_clear_object (&session);

		if (!is_online) {
			g_set_error (
				error, CAMEL_SERVICE_ERROR, CAMEL_SERVICE_ERROR_UNAVAILABLE,
				_("Message send in offline mode is disabled"));
			return FALSE;
		}
	}

	if (camel_sendmail_settings_get_use_custom_binary (settings)) {
		custom_binary = camel_sendmail_settings_dup_custom_binary (settings);
		if (custom_binary && *custom_binary)
			binary = custom_binary;
	}

	if (camel_sendmail_settings_get_use_custom_args (settings)) {
		custom_args = camel_sendmail_settings_dup_custom_args (settings);
		/* means no arguments used */
		if (!custom_args)
			custom_args = g_strdup ("");
	}

	g_object_unref (settings);

	len = camel_address_length (recipients);
	for (i = 0; i < len; i++) {
		success = camel_internet_address_get (
			CAMEL_INTERNET_ADDRESS (recipients), i, NULL, &addr);

		if (!success) {
			g_set_error (
				error, CAMEL_ERROR, CAMEL_ERROR_GENERIC,
				_("Could not parse recipient list"));
			g_free (custom_binary);
			g_free (custom_args);

			return FALSE;
		}
	}

	argv_arr = parse_sendmail_args (
		binary,
		custom_args ? custom_args : "-i -f %F -- %R",
		from_addr,
		recipients);

	if (!argv_arr) {
		g_set_error (
			error, CAMEL_ERROR, CAMEL_ERROR_GENERIC,
			_("Could not parse arguments"));

		g_free (custom_binary);
		g_free (custom_args);

		return FALSE;
	}

	/* unlink the bcc headers */
	previous_headers = camel_medium_dup_headers (CAMEL_MEDIUM (message));
	camel_medium_remove_header (CAMEL_MEDIUM (message), "Bcc");

	if (pipe (fd) == -1) {
		g_set_error (
			error, G_IO_ERROR,
			g_io_error_from_errno (errno),
			_("Could not create pipe to “%s”: %s: "
			"mail not sent"), binary, g_strerror (errno));

		/* restore the bcc headers */
		for (ii = 0; camel_name_value_array_get (previous_headers, ii, &header_name, &header_value); ii++) {
			if (!g_ascii_strcasecmp (header_name, "Bcc")) {
				camel_medium_add_header (CAMEL_MEDIUM (message), header_name, header_value);
			}
		}

		camel_name_value_array_free (previous_headers);
		g_free (custom_binary);
		g_free (custom_args);
		g_ptr_array_free (argv_arr, TRUE);

		return FALSE;
	}

	/* Block SIGCHLD so the calling application doesn't notice
	 * sendmail exiting before we do.
	 */
	sigemptyset (&mask);
	sigaddset (&mask, SIGCHLD);
	sigprocmask (SIG_BLOCK, &mask, &omask);

	pid = fork ();
	switch (pid) {
	case -1:
		g_set_error (
			error, G_IO_ERROR,
			g_io_error_from_errno (errno),
			_("Could not fork “%s”: %s: "
			"mail not sent"), binary, g_strerror (errno));
		close (fd[0]);
		close (fd[1]);
		sigprocmask (SIG_SETMASK, &omask, NULL);

		/* restore the bcc headers */
		for (ii = 0; camel_name_value_array_get (previous_headers, ii, &header_name, &header_value); ii++) {
			if (!g_ascii_strcasecmp (header_name, "Bcc")) {
				camel_medium_add_header (CAMEL_MEDIUM (message), header_name, header_value);
			}
		}

		camel_name_value_array_free (previous_headers);
		g_free (custom_binary);
		g_free (custom_args);
		g_ptr_array_free (argv_arr, TRUE);

		return FALSE;
	case 0:
		/* Child process */
		nullfd = open ("/dev/null", O_RDWR);
		dup2 (fd[0], STDIN_FILENO);
		if (nullfd != -1) {
			/*dup2 (nullfd, STDOUT_FILENO);
			  dup2 (nullfd, STDERR_FILENO);*/
			close (nullfd);
		}
		close (fd[1]);

		execv (binary, (gchar **) argv_arr->pdata);
		_exit (255);
	}

	g_ptr_array_free (argv_arr, TRUE);

	/* Parent process. Write the message out. */
	close (fd[0]);
	out = camel_stream_fs_new_with_fd (fd[1]);

	/* XXX Workaround for lame sendmail implementations
	 *     that can't handle CRLF eoln sequences. */
	filter = camel_stream_filter_new (out);
	crlf = camel_mime_filter_crlf_new (
		CAMEL_MIME_FILTER_CRLF_DECODE,
		CAMEL_MIME_FILTER_CRLF_MODE_CRLF_ONLY);
	camel_stream_filter_add (CAMEL_STREAM_FILTER (filter), crlf);
	g_object_unref (crlf);
	g_object_unref (out);

	out = (CamelStream *) filter;
	if (camel_data_wrapper_write_to_stream_sync (
		CAMEL_DATA_WRAPPER (message), out, cancellable, error) == -1
	    || camel_stream_close (out, cancellable, error) == -1) {
		g_object_unref (out);
		g_prefix_error (error, _("Could not send message: "));

		/* Wait for sendmail to exit. */
		while (waitpid (pid, &wstat, 0) == -1 && errno == EINTR)
			;

		sigprocmask (SIG_SETMASK, &omask, NULL);

		/* restore the bcc headers */
		for (ii = 0; camel_name_value_array_get (previous_headers, ii, &header_name, &header_value); ii++) {
			if (!g_ascii_strcasecmp (header_name, "Bcc")) {
				camel_medium_add_header (CAMEL_MEDIUM (message), header_name, header_value);
			}
		}

		camel_name_value_array_free (previous_headers);
		g_free (custom_binary);
		g_free (custom_args);

		return FALSE;
	}

	g_object_unref (out);

	/* Wait for sendmail to exit. */
	while (waitpid (pid, &wstat, 0) == -1 && errno == EINTR)
		;

	sigprocmask (SIG_SETMASK, &omask, NULL);

	/* restore the bcc headers */
	for (ii = 0; camel_name_value_array_get (previous_headers, ii, &header_name, &header_value); ii++) {
		if (!g_ascii_strcasecmp (header_name, "Bcc")) {
			camel_medium_add_header (CAMEL_MEDIUM (message), header_name, header_value);
		}
	}

	camel_name_value_array_free (previous_headers);

	if (!WIFEXITED (wstat)) {
		g_set_error (
			error, CAMEL_ERROR, CAMEL_ERROR_GENERIC,
			_("“%s” exited with signal %s: mail not sent."),
			binary, g_strsignal (WTERMSIG (wstat)));
		g_free (custom_binary);
		g_free (custom_args);

		return FALSE;
	} else if (WEXITSTATUS (wstat) != 0) {
		if (WEXITSTATUS (wstat) == 255) {
			g_set_error (
				error, CAMEL_ERROR, CAMEL_ERROR_GENERIC,
				_("Could not execute “%s”: mail not sent."),
				binary);
		} else {
			g_set_error (
				error, CAMEL_ERROR, CAMEL_ERROR_GENERIC,
				_("“%s” exited with status %d: "
				"mail not sent."),
				binary, WEXITSTATUS (wstat));
		}
		g_free (custom_binary);
		g_free (custom_args);

		return FALSE;
	}

	g_free (custom_binary);
	g_free (custom_args);

	return TRUE;
}
Esempio n. 24
0
int
main(int argc, char **argv)
{
	int ch;
	int error = 0;
	extern char *__progname;

	while ((ch = getopt(argc, argv, "abcdDfijkKlmnqrstuv:")) != -1)
		switch (ch) {
		case 'a':
			/* print all commands */
			aflag = 1;
			break;
		case 'b':
			/* sort by per-call user/system time average */
			bflag = 1;
			sa_cmp = cmp_avgusrsys;
			break;
		case 'c':
			/* print percentage total time */
			cflag = 1;
			break;
		case 'd':
			/* sort by averge number of disk I/O ops */
			dflag = 1;
			sa_cmp = cmp_avgdkio;
			break;
		case 'D':
			/* print and sort by total disk I/O ops */
			Dflag = 1;
			sa_cmp = cmp_dkio;
			break;
		case 'f':
			/* force no interactive threshold comprison */
			fflag = 1;
			break;
		case 'i':
			/* do not read in summary file */
			iflag = 1;
			break;
		case 'j':
			/* instead of total minutes, give sec/call */
			jflag = 1;
			break;
		case 'k':
			/* sort by cpu-time average memory usage */
			kflag = 1;
			sa_cmp = cmp_avgcpumem;
			break;
		case 'K':
			/* print and sort by cpu-storage integral */
			sa_cmp = cmp_cpumem;
			Kflag = 1;
			break;
		case 'l':
			/* separate system and user time */
			lflag = 1;
			break;
		case 'm':
			/* print procs and time per-user */
			mflag = 1;
			break;
		case 'n':
			/* sort by number of calls */
			sa_cmp = cmp_calls;
			break;
		case 'q':
			/* quiet; error messages only */
			qflag = 1;
			break;
		case 'r':
			/* reverse order of sort */
			rflag = 1;
			break;
		case 's':
			/* merge accounting file into summaries */
			sflag = 1;
			break;
		case 't':
			/* report ratio of user and system times */
			tflag = 1;
			break;
		case 'u':
			/* first, print uid and command name */
			uflag = 1;
			break;
		case 'v':
			/* cull junk */
			vflag = 1;
			cutoff = atoi(optarg);
			break;
		case '?':
		default:
			(void)fprintf(stderr,
			    "usage: %s [-abcDdfijKklmnqrstu] [-v cutoff]"
			    " [file ...]\n", __progname);
			exit(1);
		}

	argc -= optind;
	argv += optind;

	/* various argument checking */
	if (fflag && !vflag)
		errx(1, "only one of -f requires -v");
	if (fflag && aflag)
		errx(1, "only one of -a and -v may be specified");
	/* XXX need more argument checking */

	if (!uflag) {
		/* initialize tables */
		if ((sflag || (!mflag && !qflag)) && pacct_init() != 0)
			errx(1, "process accounting initialization failed");
		if ((sflag || (mflag && !qflag)) && usracct_init() != 0)
			errx(1, "user accounting initialization failed");
	}

	if (argc == 0) {
		argc = dfltargc;
		argv = dfltargv;
	}

	/* for each file specified */
	for (; argc > 0; argc--, argv++) {
		int	fd;

		/*
		 * load the accounting data from the file.
		 * if it fails, go on to the next file.
		 */
		fd = acct_load(argv[0], sflag);
		if (fd < 0)
			continue;

		if (!uflag && sflag) {
#ifndef DEBUG
			sigset_t nmask, omask;
			int unmask = 1;

			/*
			 * block most signals so we aren't interrupted during
			 * the update.
			 */
			if (sigfillset(&nmask) == -1) {
				warn("sigfillset");
				unmask = 0;
				error = 1;
			}
			if (unmask &&
			    (sigprocmask(SIG_BLOCK, &nmask, &omask) == -1)) {
				warn("couldn't set signal mask ");
				unmask = 0;
				error = 1;
			}
#endif /* DEBUG */

			/*
			 * truncate the accounting data file ASAP, to avoid
			 * losing data.  don't worry about errors in updating
			 * the saved stats; better to underbill than overbill,
			 * but we want every accounting record intact.
			 */
			if (ftruncate(fd, 0) == -1) {
				warn("couldn't truncate %s", *argv);
				error = 1;
			}

			/*
			 * update saved user and process accounting data.
			 * note errors for later.
			 */
			if (pacct_update() != 0 || usracct_update() != 0)
				error = 1;

#ifndef DEBUG
			/*
			 * restore signals
			 */
			if (unmask &&
			    (sigprocmask(SIG_SETMASK, &omask, NULL) == -1)) {
				warn("couldn't restore signal mask");
				error = 1;
			}
#endif /* DEBUG */
		}

		/*
		 * close the opened accounting file
		 */
		if (close(fd) == -1) {
			warn("close %s", *argv);
			error = 1;
		}
	}

	if (!uflag && !qflag) {
		/* print any results we may have obtained. */
		if (!mflag)
			pacct_print();
		else
			usracct_print();
	}

	if (!uflag) {
		/* finally, deallocate databases */
		if (sflag || (!mflag && !qflag))
			pacct_destroy();
		if (sflag || (mflag && !qflag))
			usracct_destroy();
	}

	exit(error);
}
Esempio n. 25
0
int schedule_unload(pid_t pid, FAR struct binary_s *bin)
{
  struct sigaction act;
  struct sigaction oact;
  sigset_t sigset;
  irqstate_t flags;
  int errorcode;
  int ret;

  /* Make sure that SIGCHLD is unmasked */

  (void)sigemptyset(&sigset);
  (void)sigaddset(&sigset, SIGCHLD);
  ret = sigprocmask(SIG_UNBLOCK, &sigset, NULL);
  if (ret != OK)
    {
      /* The errno value will get trashed by the following debug output */

      errorcode = get_errno();
      bvdbg("ERROR: sigprocmask failed: %d\n", ret);
      goto errout;
    }

  /* Add the structure to the list.  We want to do this *before* connecting
   * the signal handler.  This does, however, make error recovery more
   * complex if sigaction() fails below because then we have to remove the
   * unload structure for the list in an unexpected context.
   */

  unload_list_add(pid, bin);

  /* Register the SIGCHLD handler */

  act.sa_sigaction = unload_callback;
  act.sa_flags     = SA_SIGINFO;

  (void)sigfillset(&act.sa_mask);
  (void)sigdelset(&act.sa_mask, SIGCHLD);

  ret = sigaction(SIGCHLD, &act, &oact);
  if (ret != OK)
    {
      /* The errno value will get trashed by the following debug output */

      errorcode = get_errno();
      bvdbg("ERROR: sigaction failed: %d\n" , ret);

      /* Emergency removal from the list */

      flags = irqsave();
      if (unload_list_remove(pid) != bin)
        {
          blldbg("ERROR: Failed to remove structure\n");
        }
      
      goto errout;
    }

  return OK;

errout:
  set_errno(errorcode);
  return ERROR;
}
Esempio n. 26
0
int main(int argc, char *argv[]) {
    atexit(cleanup);
    sigset_t mask;
    sigfillset(&mask);
    sigdelset(&mask, SIGUSR1);
    sigprocmask(SIG_SETMASK, &mask, NULL);
    struct sigaction act;
    memset(&act, 0, sizeof act);
    act.sa_handler = sigint_handler;
    sigaction(SIGUSR1, &act, NULL);

    srand(time(NULL));

    shm_id = shmget(SHM_KEY, MEM_SIZE, S_IRUSR);
    sem_id = semget(SEM_KEY, 0, S_IWUSR | S_IRUSR);
    if (shm_id < 0 || sem_id < 0) {
        printf("Error while opening shared memory and/or semaphores occurred.\n");
        return 1;
    }

    shm = shmat(shm_id, NULL, 0);
    if (shm == (void *)-1) {
        printf("Error while accessing shared memory occurred.\n");
        return 1;
    }
    struct sembuf sem_op;
    sem_op.sem_flg = 0;
    int task_index;
    int tasks_num;
    struct timeval tval;
    while (1) {
        sem_op.sem_num = 0;
        sem_op.sem_op = -1;
        if (semop(sem_id, &sem_op, 1) == -1)
            on_host_closed();

        sem_op.sem_num = 2;
        if (semop(sem_id, &sem_op, 1) == -1)
            on_host_closed();
        task_index = shm->start_index;
        shm->start_index = (task_index + 1) % ARRAY_LEN;

        tasks_num = shm->end_index - shm->start_index;
        if (tasks_num < 0)
            tasks_num += ARRAY_LEN;

        gettimeofday(&tval, NULL);
        printf("%d %ld.%ld Get task from position %d. Number of waiting tasks: %d.\n", getpid(), tval.tv_sec, tval.tv_usec/1000, task_index, tasks_num);
        fflush(stdout);
        sem_op.sem_num = 2;
        sem_op.sem_op = 1;
        if (semop(sem_id, &sem_op, 1) == -1)
            on_host_closed();
        sem_op.sem_num = 1;
        sem_op.sem_op = 1;
        if (semop(sem_id, &sem_op, 1) == -1)
            on_host_closed();

        nanosleep(&delay, NULL);
    }
}
Esempio n. 27
0
int
main(int argc, char **argv) {
	struct sigaction sa;
	int ch;

	enum { FORCE_OPTION = CHAR_MAX + 1 };

	static const struct option longopts[] = {
		{ "append",	no_argument,	   NULL, 'a' },
		{ "command",	required_argument, NULL, 'c' },
		{ "return",	no_argument,	   NULL, 'e' },
		{ "flush",	no_argument,	   NULL, 'f' },
		{ "force",	no_argument,	   NULL, FORCE_OPTION, },
		{ "quiet",	no_argument,	   NULL, 'q' },
		{ "timing",	optional_argument, NULL, 't' },
		{ "version",	no_argument,	   NULL, 'V' },
		{ "help",	no_argument,	   NULL, 'h' },
		{ NULL,		0, NULL, 0 }
	};

	setlocale(LC_ALL, "");
	setlocale(LC_NUMERIC, "C");	/* see comment above */
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while ((ch = getopt_long(argc, argv, "ac:efqt::Vh", longopts, NULL)) != -1)
		switch(ch) {
		case 'a':
			aflg = 1;
			break;
		case 'c':
			cflg = optarg;
			break;
		case 'e':
			eflg = 1;
			break;
		case 'f':
			fflg = 1;
			break;
		case FORCE_OPTION:
			forceflg = 1;
			break;
		case 'q':
			qflg = 1;
			break;
		case 't':
			if (optarg && !(timingfd = fopen(optarg, "w")))
				err(EXIT_FAILURE, _("cannot open %s"), optarg);
			tflg = 1;
			break;
		case 'V':
			printf(_("%s from %s\n"), program_invocation_short_name,
						  PACKAGE_STRING);
			exit(EXIT_SUCCESS);
			break;
		case 'h':
			usage(stdout);
			break;
		case '?':
		default:
			usage(stderr);
		}
	argc -= optind;
	argv += optind;

	if (argc > 0)
		fname = argv[0];
	else {
		fname = DEFAULT_OUTPUT;
		die_if_link(fname);
	}

	if ((fscript = fopen(fname, aflg ? "a" : "w")) == NULL) {
		warn(_("cannot open %s"), fname);
		fail();
	}

	shell = getenv("SHELL");
	if (shell == NULL)
		shell = _PATH_BSHELL;

	getmaster();
	if (!qflg)
		printf(_("Script started, file is %s\n"), fname);
	fixtty();

#ifdef HAVE_LIBUTEMPTER
	utempter_add_record(master, NULL);
#endif
	/* setup SIGCHLD handler */
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sa.sa_handler = finish;
	sigaction(SIGCHLD, &sa, NULL);

	/* init mask for SIGCHLD */
	sigprocmask(SIG_SETMASK, NULL, &block_mask);
	sigaddset(&block_mask, SIGCHLD);

	sigprocmask(SIG_SETMASK, &block_mask, &unblock_mask);
	child = fork();
	sigprocmask(SIG_SETMASK, &unblock_mask, NULL);

	if (child < 0) {
		warn(_("fork failed"));
		fail();
	}
	if (child == 0) {

		sigprocmask(SIG_SETMASK, &block_mask, NULL);
		subchild = child = fork();
		sigprocmask(SIG_SETMASK, &unblock_mask, NULL);

		if (child < 0) {
			warn(_("fork failed"));
			fail();
		}
		if (child)
			dooutput();
		else
			doshell();
	} else {
		sa.sa_handler = resize;
		sigaction(SIGWINCH, &sa, NULL);
	}
	doinput();

	return EXIT_SUCCESS;
}
Esempio n. 28
0
int main (int argc, char **argv)
{
	/* master file descriptor list */
	fd_set used_fds, serv_fds, read_fds;

	/* working structs */
	struct addrinfo hints;
	struct sigaction sa;
	struct config conf;

	/* signal mask */
	sigset_t ss;

	/* maximum file descriptor number */
	int cur_fd, max_fd = 0;

#ifdef HAVE_TLS
	int tls = 0;
	int keys = 0;
#endif

	int bound = 0;
	int nofork = 0;

	/* args */
	int opt;
	char bind[128];
	char *port = NULL;

#if defined(HAVE_TLS) || defined(HAVE_LUA)
	/* library handle */
	void *lib;
#endif

	/* clear the master and temp sets */
	FD_ZERO(&used_fds);
	FD_ZERO(&serv_fds);
	FD_ZERO(&read_fds);

	/* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, NULL);

	sa.sa_handler = uh_sigchld;
	sigaction(SIGCHLD, &sa, NULL);

	sa.sa_handler = uh_sigterm;
	sigaction(SIGINT,  &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	/* defer SIGCHLD */
	sigemptyset(&ss);
	sigaddset(&ss, SIGCHLD);
	sigprocmask(SIG_BLOCK, &ss, NULL);

	/* prepare addrinfo hints */
	memset(&hints, 0, sizeof(hints));
	hints.ai_family   = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags    = AI_PASSIVE;

	/* parse args */
	memset(&conf, 0, sizeof(conf));
	memset(bind, 0, sizeof(bind));

#ifdef HAVE_TLS
	/* load TLS plugin */
	if( ! (lib = dlopen("uhttpd_tls.so", RTLD_LAZY | RTLD_GLOBAL)) )
	{
		fprintf(stderr,
			"Notice: Unable to load TLS plugin - disabling SSL support! "
			"(Reason: %s)\n", dlerror()
		);
	}
	else
	{
		/* resolve functions */
		if( !(conf.tls_init   = dlsym(lib, "uh_tls_ctx_init"))      ||
		    !(conf.tls_cert   = dlsym(lib, "uh_tls_ctx_cert"))      ||
		    !(conf.tls_key    = dlsym(lib, "uh_tls_ctx_key"))       ||
		    !(conf.tls_free   = dlsym(lib, "uh_tls_ctx_free"))      ||
			!(conf.tls_accept = dlsym(lib, "uh_tls_client_accept")) ||
			!(conf.tls_close  = dlsym(lib, "uh_tls_client_close"))  ||
			!(conf.tls_recv   = dlsym(lib, "uh_tls_client_recv"))   ||
			!(conf.tls_send   = dlsym(lib, "uh_tls_client_send"))
		) {
			fprintf(stderr,
				"Error: Failed to lookup required symbols "
				"in TLS plugin: %s\n", dlerror()
			);
			exit(1);
		}

		/* init SSL context */
		if( ! (conf.tls = conf.tls_init()) )
		{
			fprintf(stderr, "Error: Failed to initalize SSL context\n");
			exit(1);
		}
	}
#endif

	while( (opt = getopt(argc, argv,
		"fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:x:i:t:T:")) > 0
	) {
		switch(opt)
		{
			/* [addr:]port */
			case 'p':
			case 's':
				if( (port = strrchr(optarg, ':')) != NULL )
				{
					if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
						memcpy(bind, optarg + 1,
							min(sizeof(bind), (int)(port - optarg) - 2));
					else
						memcpy(bind, optarg,
							min(sizeof(bind), (int)(port - optarg)));

					port++;
				}
				else
				{
					port = optarg;
				}

#ifdef HAVE_TLS
				if( opt == 's' )
				{
					if( !conf.tls )
					{
						fprintf(stderr,
							"Notice: TLS support is disabled, "
							"ignoring '-s %s'\n", optarg
						);
						continue;
					}

					tls = 1;
				}
#endif

				/* bind sockets */
				bound += uh_socket_bind(
					&serv_fds, &max_fd, bind[0] ? bind : NULL, port,
					&hints,	(opt == 's'), &conf
				);

				memset(bind, 0, sizeof(bind));
				break;

#ifdef HAVE_TLS
			/* certificate */
			case 'C':
				if( conf.tls )
				{
					if( conf.tls_cert(conf.tls, optarg) < 1 )
					{
						fprintf(stderr,
							"Error: Invalid certificate file given\n");
						exit(1);
					}

					keys++;
				}

				break;

			/* key */
			case 'K':
				if( conf.tls )
				{
					if( conf.tls_key(conf.tls, optarg) < 1 )
					{
						fprintf(stderr,
							"Error: Invalid private key file given\n");
						exit(1);
					}

					keys++;
				}

				break;
#endif

			/* docroot */
			case 'h':
				if( ! realpath(optarg, conf.docroot) )
				{
					fprintf(stderr, "Error: Invalid directory %s: %s\n",
						optarg, strerror(errno));
					exit(1);
				}
				break;

			/* error handler */
			case 'E':
				if( (strlen(optarg) == 0) || (optarg[0] != '/') )
				{
					fprintf(stderr, "Error: Invalid error handler: %s\n",
						optarg);
					exit(1);
				}
				conf.error_handler = optarg;
				break;

			/* index file */
			case 'I':
				if( (strlen(optarg) == 0) || (optarg[0] == '/') )
				{
					fprintf(stderr, "Error: Invalid index page: %s\n",
						optarg);
					exit(1);
				}
				conf.index_file = optarg;
				break;

			/* don't follow symlinks */
			case 'S':
				conf.no_symlinks = 1;
				break;

			/* don't list directories */
			case 'D':
				conf.no_dirlists = 1;
				break;

			case 'R':
				conf.rfc1918_filter = 1;
				break;

#ifdef HAVE_CGI
			/* cgi prefix */
			case 'x':
				conf.cgi_prefix = optarg;
				break;

			/* interpreter */
			case 'i':
				if( (optarg[0] == '.') && (port = strchr(optarg, '=')) )
				{
					*port++ = 0;
					uh_interpreter_add(optarg, port);
				}
				else
				{
					fprintf(stderr, "Error: Invalid interpreter: %s\n",
						optarg);
					exit(1);
				}
				break;
#endif

#ifdef HAVE_LUA
			/* lua prefix */
			case 'l':
				conf.lua_prefix = optarg;
				break;

			/* lua handler */
			case 'L':
				conf.lua_handler = optarg;
				break;
#endif

#if defined(HAVE_CGI) || defined(HAVE_LUA)
			/* script timeout */
			case 't':
				conf.script_timeout = atoi(optarg);
				break;
#endif

			/* network timeout */
			case 'T':
				conf.network_timeout = atoi(optarg);
				break;

			/* no fork */
			case 'f':
				nofork = 1;
				break;

			/* urldecode */
			case 'd':
				if( (port = malloc(strlen(optarg)+1)) != NULL )
				{
					memset(port, 0, strlen(optarg)+1);
					uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
					printf("%s", port);
					free(port);
					exit(0);
				}
				break;

			/* basic auth realm */
			case 'r':
				conf.realm = optarg;
				break;

			/* md5 crypt */
			case 'm':
				printf("%s\n", crypt(optarg, "$1$"));
				exit(0);
				break;

			/* config file */
			case 'c':
				conf.file = optarg;
				break;

			default:
				fprintf(stderr,
					"Usage: %s -p [addr:]port [-h docroot]\n"
					"	-f              Do not fork to background\n"
					"	-c file         Configuration file, default is '/etc/httpd.conf'\n"
					"	-p [addr:]port  Bind to specified address and port, multiple allowed\n"
#ifdef HAVE_TLS
					"	-s [addr:]port  Like -p but provide HTTPS on this port\n"
					"	-C file         ASN.1 server certificate file\n"
					"	-K file         ASN.1 server private key file\n"
#endif
					"	-h directory    Specify the document root, default is '.'\n"
					"	-E string       Use given virtual URL as 404 error handler\n"
					"	-I string       Use given filename as index page for directories\n"
					"	-S              Do not follow symbolic links outside of the docroot\n"
					"	-D              Do not allow directory listings, send 403 instead\n"
					"	-R              Enable RFC1918 filter\n"
#ifdef HAVE_LUA
					"	-l string       URL prefix for Lua handler, default is '/lua'\n"
					"	-L file         Lua handler script, omit to disable Lua\n"
#endif
#ifdef HAVE_CGI
					"	-x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
					"	-i .ext=path    Use interpreter at path for files with the given extension\n"
#endif
#if defined(HAVE_CGI) || defined(HAVE_LUA)
					"	-t seconds      CGI and Lua script timeout in seconds, default is 60\n"
#endif
					"	-T seconds      Network timeout in seconds, default is 30\n"
					"	-d string       URL decode given string\n"
					"	-r string       Specify basic auth realm\n"
					"	-m string       MD5 crypt given string\n"
					"\n", argv[0]
				);

				exit(1);
		}
	}

#ifdef HAVE_TLS
	if( (tls == 1) && (keys < 2) )
	{
		fprintf(stderr, "Error: Missing private key or certificate file\n");
		exit(1);
	}
#endif

	if( bound < 1 )
	{
		fprintf(stderr, "Error: No sockets bound, unable to continue\n");
		exit(1);
	}

	/* default docroot */
	if( !conf.docroot[0] && !realpath(".", conf.docroot) )
	{
		fprintf(stderr, "Error: Can not determine default document root: %s\n",
			strerror(errno));
		exit(1);
	}

	/* default realm */
	if( ! conf.realm )
		conf.realm = "Protected Area";

	/* config file */
	uh_config_parse(&conf);

	/* default network timeout */
	if( conf.network_timeout <= 0 )
		conf.network_timeout = 30;

#if defined(HAVE_CGI) || defined(HAVE_LUA)
	/* default script timeout */
	if( conf.script_timeout <= 0 )
		conf.script_timeout = 60;
#endif

#ifdef HAVE_CGI
	/* default cgi prefix */
	if( ! conf.cgi_prefix )
		conf.cgi_prefix = "/cgi-bin";
#endif

#ifdef HAVE_LUA
	/* load Lua plugin */
	if( ! (lib = dlopen("uhttpd_lua.so", RTLD_LAZY | RTLD_GLOBAL)) )
	{
		fprintf(stderr,
			"Notice: Unable to load Lua plugin - disabling Lua support! "
			"(Reason: %s)\n", dlerror()
		);
	}
	else
	{
		/* resolve functions */
		if( !(conf.lua_init    = dlsym(lib, "uh_lua_init"))    ||
		    !(conf.lua_close   = dlsym(lib, "uh_lua_close"))   ||
		    !(conf.lua_request = dlsym(lib, "uh_lua_request"))
		) {
			fprintf(stderr,
				"Error: Failed to lookup required symbols "
				"in Lua plugin: %s\n", dlerror()
			);
			exit(1);
		}

		/* init Lua runtime if handler is specified */
		if( conf.lua_handler )
		{
			/* default lua prefix */
			if( ! conf.lua_prefix )
				conf.lua_prefix = "/lua";

			conf.lua_state = conf.lua_init(conf.lua_handler);
		}
	}
#endif

	/* fork (if not disabled) */
	if( ! nofork )
	{
		switch( fork() )
		{
			case -1:
				perror("fork()");
				exit(1);

			case 0:
				/* daemon setup */
				if( chdir("/") )
					perror("chdir()");

				if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
					dup2(cur_fd, 0);

				if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
					dup2(cur_fd, 1);

				if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
					dup2(cur_fd, 2);

				break;

			default:
				exit(0);
		}
	}

	/* server main loop */
	uh_mainloop(&conf, serv_fds, max_fd);

#ifdef HAVE_LUA
	/* destroy the Lua state */
	if( conf.lua_state != NULL )
		conf.lua_close(conf.lua_state);
#endif

	return 0;
}
Esempio n. 29
0
/*
 *  割込みマスクの参照
 */
SYSCALL ER
get_ims(IMS *p_ims)
{
    sigprocmask(SIG_SETMASK,p_ims,0);        
	return(E_OK);
}
Esempio n. 30
0
int main(int argc, char *argv[]) 
{
	int o;
	while(-1 != (o = getopt(argc, argv, "f:m:hvVDpt"))) {
		switch(o) {
		case 'f':
			strcpy(g_scan_interface, optarg);	
			break;
		}
	}

	//- Check if same process is running.
	FILE *fp = fopen(LIGHTTPD_ARPPING_PID_FILE_PATH, "r");
	if (fp) {
		fclose(fp);
		exit(EXIT_FAILURE);
		return 0;
	}
	
	//- Write PID file
	pid_t pid = getpid();
	fp = fopen(LIGHTTPD_ARPPING_PID_FILE_PATH, "w");
	if (!fp) {
		exit(EXIT_FAILURE);
	}
	fprintf(fp, "%d\n", pid);
	fclose(fp);

#if EMBEDDED_EANBLE
	sigset_t sigs_to_catch;

	//- set the signal handler
    sigemptyset(&sigs_to_catch);
    sigaddset(&sigs_to_catch, SIGTERM);
	sigaddset(&sigs_to_catch, SIGUSR1);
    sigprocmask(SIG_UNBLOCK, &sigs_to_catch, NULL);

    signal(SIGTERM, sigaction_handler);  
	signal(SIGUSR1, sigaction_handler);
#else
	struct sigaction act;
	memset(&act, 0, sizeof(act));
	act.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &act, NULL);
	sigaction(SIGUSR1, &act, NULL);

	act.sa_sigaction = sigaction_handler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_SIGINFO;

	sigaction(SIGINT,  &act, NULL);
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGHUP,  &act, NULL);
	sigaction(SIGALRM, &act, NULL);
	sigaction(SIGCHLD, &act, NULL);	
	sigaction(SIGUSR1, &act, NULL);	
#endif
	
	//int          dbglv = -1;//9;
	int          dbglv = 0;
	smbc_init(get_auth_data_fn, dbglv);
	
	start_scan_sambaserver(0);
	
	time_t prv_ts = 0;
	while (!is_shutdown) {

		sleep(10);
		
		time_t cur_ts = time(NULL);
		
#if EMBEDDED_EANBLE
		if(prv_ts == 0 || cur_ts - prv_ts >= ARP_TIME_INTERVAL){
			dumparptable();	
			query_one_hostname();
			prv_ts = cur_ts;
		}
#else		
		if( prv_ts == 0 || cur_ts - prv_ts >= ARP_TIME_INTERVAL ){	
			on_arpping_timer_handler2(0);	
			prv_ts = cur_ts;			
		}		
#endif
		
		if (g_kill_list) {
			smb_srv_info_t *c;
			smb_srv_info_t *tmp = NULL;

			g_kill_list = 0;
			c = smb_srv_info_list;
			if (c != NULL) {
				while (1) {
					int end = (c->next == NULL) ? 1 : 0;

					if (end == 0) {
						tmp = c->next;
						Cdbg(DBE, "next, ip=%s", tmp->ip->ptr);
					} else
						tmp = NULL;

					if (c) {
						Cdbg(DBE, "remove , ip=[%s]", c->ip->ptr);
						DLIST_REMOVE(smb_srv_info_list, c);
						free(c);
					} else
						break;

					if (end == 1)
						break;

					c = tmp;
				}
			}
			g_threadIndex = 0;
		}
  	}

	Cdbg(DBE, "Success to terminate lighttpd-arpping.....");
	
	exit(EXIT_SUCCESS);

	return 0;
}