Esempio n. 1
0
int main (int argc, char **argv)   /* argc holds command line argument count */
{                                  /* argv holds the arguments */

    int n_waiting;              /* number waiting for the semaphore */
    char name[10];              /* give your process a name to distinguish it */
    if ( argc == 2 ) {          /* read in process name from command line */
      strcpy(name,argv[1]);     /* argv[0] is the name of the executable 
                                   argv[1] is the first command line arg */
      printf("process name: %s\n",name);
    } else {
      printf("USAGE: sem_test <process name> \n");
      exit(EXIT_FAILURE);
    } 
    char pathname[30];
    int semid;
    struct sembuf sops[2];  /* will hold two operations */

    /* Generate a pseudo-unique ipc key */
    key_t ipckey;
    getcwd(pathname,30);
    strcat(pathname,"foo");  /* foo must exist in your directory */
    ipckey = ftok(pathname, 42);  
                                        
    int nsems = 1;  /* the number of semaphores you want in the set */
    /* create and set perms on the set; 4 is read, 2 is alter, 6 is BOTH */
    semid = semget(ipckey, nsems, 0666 | IPC_CREAT);
    if (semid < 0) {
          printf("Error - %s\n", strerror(errno));
          _exit(1);
    }

    my_semun.val = 1;
    semctl(semid, 0, SETVAL, my_semun);
    int sem_value = semctl(semid, 0, GETVAL);
    printf("Sem#0 value: %d\n",sem_value);

    /* now set it back */
    my_semun.val = 0;
    semctl(semid, 0, SETVAL, my_semun);

    /* initialize sembuf struct for semaphore operations */
    sops[0].sem_num = 0;  /* operation applies to the first semaphore in  set */
    sops[0].sem_flg = SEM_UNDO; /* undo action if premature exit */

    sops[1].sem_num = 0;        /* op 2 also applies to the first semaphore */
    sops[1].sem_flg = SEM_UNDO; 

    while(1)  
    {

        /* these two semaphore operations are be executed atomically */
        sops[0].sem_op = 0; /* 1st operation: wait until sem value is zero */
        sops[1].sem_op = 1; /* 2nd operation: add 1 to semaphore value */

        /* perform the two operations */
        semop(semid, sops, 2); 

        /* use semctl to get actual value of semaphore */
        n_waiting = semctl(semid, 0, GETZCNT);
        printf("%s: %d waiting for semaphore \n", name, n_waiting);

        printf("[%s] I have the semaphore\n", name);
        sleep(rand() % 3); /* critical section, take a nap for 0-2 seconds */

        /* define second operation */
        sops[0].sem_op = -1; /* decrement semaphore value by 1 */

        semop(semid, sops, 1);
        printf("[%s] Released semaphore\n", name);

        sleep(rand() % 3); /* Sleep 0-2 seconds */
    }

  
    exit(EXIT_SUCCESS);
}
int BlsChildChannel::clean()
{
    log_error("process will exit, may be master process is freezed.");
    _exit(0);
}
void DCU_initialize()
{
	if (DCU_STATE(DCU_INITIALIZED))
	{
		return;
	}

	if (DCU_STATE(DCU_MUTEX_INITED))
	{
		DCU_MutexScopedLock lock(DCU_mutex);
		if (DCU_STATE(DCU_INITIALIZED))
		{
			return;
		}
		else
		{
			fprintf(DCU_FALLBACK_STREAM, "DynamicCheckUp Concurrency error.\n");
			_exit(1);
		}
	}

	if (pthread_mutex_init(&DCU_mutex, 0) < 0)
	{
		fprintf(DCU_FALLBACK_STREAM, "DynamicCheckUp unable to initialize mutex\n");
		_exit(1);
	}
	else
	{
		DCU_SET_FLAG(DCU_MUTEX_INITED);
	}


	{
		DCU_MutexScopedLock lock(DCU_mutex);

		memory_space = create_mspace(0, 0);
		DCU_SET_FLAG(DCU_INITIALIZED);

		//
		// init backtrace so it wont recursively call malloc
		//
		DCU_Pointer stack[DCU_STACK_TRACE_SIZE];
		backtrace(stack, DCU_STACK_TRACE_SIZE);

		//
		// Init Tracing data
		//

		DCU_stream = DCU_FALLBACK_STREAM;
		memset(DCU_memory_stats, 0, sizeof(DCU_MemoryStats) * DCU_DYNAMIC_OPERATION_TYPES);
		memset(&DCU_memory_stats_new, 0, sizeof(DCU_MemoryStats));
		memset(&DCU_memory_stats_new_array, 0, sizeof(DCU_MemoryStats));
		memset(&DCU_memory_stats_c, 0, sizeof(DCU_MemoryStats));
		memset(DCU_null_stack, 0, sizeof(DCU_null_stack));

		//
		// Operations HashTable
		//
		DCU_memory = (DCU_OperationInfo**) DCU_malloc( DCU_HASH_TABLE_SIZE * sizeof(DCU_OperationInfo*) );
		memset(DCU_memory, 0, DCU_HASH_TABLE_SIZE * sizeof(DCU_OperationInfo*));

		//
		// Problems Linked-List
		//
		DCU_problems = 0;

		//
		// Open Log File
		//
		DCU_stream = fopen(DCU_OUTPUT_FILE, "w");
		if (DCU_stream < 0)
		{
			fprintf(DCU_FALLBACK_STREAM, "DynamicCheckUp: Unable to open %s: %m\n", DCU_OUTPUT_FILE);
			DCU_stream = DCU_FALLBACK_STREAM;
		}
		else
		{
			int flags = fcntl(fileno(DCU_stream), F_GETFD, 0);
			if (flags >= 0)
			{
				flags |= FD_CLOEXEC;
				fcntl(fileno(DCU_stream), F_SETFD, flags);
			}

			setvbuf(DCU_stream, stream_trace_buffer, _IOFBF, DCU_STREAM_BUFFER_SIZE);
		}

		DCU_SET_FLAG(DCU_TRACING);
	}

	DCU_write("DynamicCheckUp Started\n");
}
Esempio n. 4
0
static int
add2lineresolve(const char *binary, void *addr, char *buf0, size_t buflen)
{
  char *buf = buf0;
  int fd[2], r, f;
  const char *argv[5];
  pid_t p;
  char addrstr[30], *cp;

  if(access("/usr/bin/addr2line", X_OK))
    return -1;

  argv[0] = "addr2line";
  argv[1] = "-e";
  argv[2] = binary;
  argv[3] = addrstr;
  argv[4] = NULL;

  snprintf(addrstr, sizeof(addrstr), "%p", (void *)((intptr_t)addr-1));

  if(pipe(fd) == -1)
    return -1;

  if((p = fork()) == -1)
    return -1;

  if(p == 0) {
    close(0);
    close(2);
    close(fd[0]);
    dup2(fd[1], 1);
    close(fd[1]);
    if((f = open("/dev/null", O_RDWR)) == -1)
      _exit(1);

    dup2(f, 0);
    dup2(f, 2);
    close(f);

    execve("/usr/bin/addr2line", (char *const *) argv, environ);
    _exit(0);
  }

  close(fd[1]);
  *buf = 0;
  while(buflen > 1) {
    r = read(fd[0], buf, buflen);
    if(r < 1)
      break;

    buf += r;
    buflen -= r;
    *buf = 0;
    cp = strchr(buf0, '\n');
    if(cp != NULL) {
      *cp = 0;
      break;
    }
  }
  close(fd[0]);
  return 0;
}
Esempio n. 5
0
enum cmd_retval
cmd_pipe_pane_exec(struct cmd *self, struct cmd_q *cmdq)
{
	struct args		*args = self->args;
	struct client		*c;
	struct window_pane	*wp;
	char			*command;
	int			 old_fd, pipe_fd[2], null_fd;

	if (cmd_find_pane(cmdq, args_get(args, 't'), NULL, &wp) == NULL)
		return (CMD_RETURN_ERROR);
	c = cmd_find_client(cmdq, NULL, 1);

	/* Destroy the old pipe. */
	old_fd = wp->pipe_fd;
	if (wp->pipe_fd != -1) {
		bufferevent_free(wp->pipe_event);
		close(wp->pipe_fd);
		wp->pipe_fd = -1;
	}

	/* If no pipe command, that is enough. */
	if (args->argc == 0 || *args->argv[0] == '\0')
		return (CMD_RETURN_NORMAL);

	/*
	 * With -o, only open the new pipe if there was no previous one. This
	 * allows a pipe to be toggled with a single key, for example:
	 *
	 *	bind ^p pipep -o 'cat >>~/output'
	 */
	if (args_has(self->args, 'o') && old_fd != -1)
		return (CMD_RETURN_NORMAL);

	/* Open the new pipe. */
	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_fd) != 0) {
		cmdq_error(cmdq, "socketpair error: %s", strerror(errno));
		return (CMD_RETURN_ERROR);
	}

	/* Fork the child. */
	switch (fork()) {
	case -1:
		cmdq_error(cmdq, "fork error: %s", strerror(errno));
		return (CMD_RETURN_ERROR);
	case 0:
		/* Child process. */
		close(pipe_fd[0]);
		clear_signals(1);

		if (dup2(pipe_fd[1], STDIN_FILENO) == -1)
			_exit(1);
		if (pipe_fd[1] != STDIN_FILENO)
			close(pipe_fd[1]);

		null_fd = open(_PATH_DEVNULL, O_WRONLY, 0);
		if (dup2(null_fd, STDOUT_FILENO) == -1)
			_exit(1);
		if (dup2(null_fd, STDERR_FILENO) == -1)
			_exit(1);
		if (null_fd != STDOUT_FILENO && null_fd != STDERR_FILENO)
			close(null_fd);

		closefrom(STDERR_FILENO + 1);

		command = status_replace(
		    c, NULL, NULL, NULL, args->argv[0], time(NULL), 0);
		execl(_PATH_BSHELL, "sh", "-c", command, (char *) NULL);
		_exit(1);
	default:
		/* Parent process. */
		close(pipe_fd[1]);

		wp->pipe_fd = pipe_fd[0];
		wp->pipe_off = EVBUFFER_LENGTH(wp->event->input);

		wp->pipe_event = bufferevent_new(wp->pipe_fd,
		    NULL, NULL, cmd_pipe_pane_error_callback, wp);
		bufferevent_enable(wp->pipe_event, EV_WRITE);

		setblocking(wp->pipe_fd, 0);
		return (CMD_RETURN_NORMAL);
	}
}
Esempio n. 6
0
//............................................................................
void BSP_exit(void) {
    printf("Bye, Bye!");
    _exit(0);
}
Esempio n. 7
0
Int StartChildProcess ( Char *dir, Char *prg, Char *args[] )
{
/*  Int             j;       / loop variables                  */
/*  char            c[8];    / buffer for communication        */
/*  int             n;       / return value of 'select'        */
    int             slave;   /* pipe to child                   */
    Int            stream;

#if HAVE_TERMIOS_H
    struct termios  tst;     /* old and new terminal state      */
#elif HAVE_TERMIO_H
    struct termio   tst;     /* old and new terminal state      */
#elif HAVE_SGTTY_H
    struct sgttyb   tst;     /* old and new terminal state      */
#elif !defined(USE_PRECOMPILED)
/* If no way to store and reset terminal states is known, and we are
   not currently re-making the dependency list (via cnf/Makefile),
   then trigger an error. */
    #error No supported way of (re)storing terminal state is available
#endif

    /* Get a stream record */
    stream = NewStream();
    if (stream == -1)
      return -1;
    
    /* open pseudo terminal for communication with gap */
    if ( OpenPty(&PtyIOStreams[stream].ptyFD, &slave) )
    {
        Pr( "open pseudo tty failed\n", 0L, 0L);
        FreeStream(stream);
        return -1;
    }

    /* Now fiddle with the terminal sessions on the pty */
#if HAVE_TERMIOS_H
    if ( tcgetattr( slave, &tst ) == -1 )
    {
        Pr( "tcgetattr on slave pty failed\n", 0L, 0L);
        goto cleanup;

    }
    tst.c_cc[VINTR] = 0377;
    tst.c_cc[VQUIT] = 0377;
    tst.c_iflag    &= ~(INLCR|ICRNL);
    tst.c_cc[VMIN]  = 1;
    tst.c_cc[VTIME] = 0;
    tst.c_lflag    &= ~(ECHO|ICANON);
    tst.c_oflag    &= ~(ONLCR);
    if ( tcsetattr( slave, TCSANOW, &tst ) == -1 )
    {
        Pr("tcsetattr on slave pty failed\n", 0, 0 );
        goto cleanup;
    }
#elif HAVE_TERMIO_H
    if ( ioctl( slave, TCGETA, &tst ) == -1 )
    {
        Pr( "ioctl TCGETA on slave pty failed\n");
        goto cleanup;
    }
    tst.c_cc[VINTR] = 0377;
    tst.c_cc[VQUIT] = 0377;
    tst.c_iflag    &= ~(INLCR|ICRNL);
    tst.c_cc[VMIN]  = 1;
    tst.c_cc[VTIME] = 0;   
    /* Note that this is at least on Linux dangerous! 
       Therefore, we now have the HAVE_TERMIOS_H section for POSIX
       Terminal control. */
    tst.c_lflag    &= ~(ECHO|ICANON);
    if ( ioctl( slave, TCSETAW, &tst ) == -1 )
    {
        Pr( "ioctl TCSETAW on slave pty failed\n");
        goto cleanup;
    }
#elif HAVE_SGTTY_H
    if ( ioctl( slave, TIOCGETP, (char*)&tst ) == -1 )
    {
        Pr( "ioctl TIOCGETP on slave pty failed\n");
        goto cleanup;
    }
    tst.sg_flags |= RAW;
    tst.sg_flags &= ~ECHO;
    if ( ioctl( slave, TIOCSETN, (char*)&tst ) == -1 )
    {
        Pr( "ioctl on TIOCSETN slave pty failed\n");
        goto cleanup;
    }
#endif

    /* set input to non blocking operation */
    /* Not any more */

    PtyIOStreams[stream].inuse = 1;
    PtyIOStreams[stream].alive = 1;
    PtyIOStreams[stream].blocked = 0;
    PtyIOStreams[stream].changed = 0;
    /* fork */
    PtyIOStreams[stream].childPID = fork();
    if ( PtyIOStreams[stream].childPID == 0 )
    {
        /* Set up the child */
        close(PtyIOStreams[stream].ptyFD);
        if ( dup2( slave, 0 ) == -1)
            _exit(-1);
        fcntl( 0, F_SETFD, 0 );
        
        if (dup2( slave, 1 ) == -1)
            _exit(-1);
        fcntl( 1, F_SETFD, 0 );
        
        if ( chdir(dir) == -1 ) {
            _exit(-1);
        }

#if HAVE_SETPGID
        setpgid(0,0);
#endif

        execv( prg, args );

        /* This should never happen */
        close(slave);
        _exit(1);
    }

    /* Now we're back in the master */
    /* check if the fork was successful */
    if ( PtyIOStreams[stream].childPID == -1 )
    {
        Pr( "Panic: cannot fork to subprocess.\n", 0, 0);
        goto cleanup;
    }
    close(slave);
    
    
    return stream;

 cleanup:
    close(slave);
    close(PtyIOStreams[stream].ptyFD);
    PtyIOStreams[stream].inuse = 0;
    FreeStream(stream);
    return -1;
}
Esempio n. 8
0
File: mce.c Progetto: amtep/mce
/**
 * Daemonize the program
 *
 * @return TRUE if MCE is started during boot, FALSE otherwise
 */
static gboolean daemonize(void)
{
	gint retries = 0;
	gint i = 0;
	gchar str[10];

	if (getppid() == 1)
		goto EXIT;	/* Already daemonized */

	/* Detach from process group */
	switch (fork()) {
	case -1:
		/* Parent - Failure */
		mce_log(LL_CRIT, "daemonize: fork failed: %s",
			g_strerror(errno));
		mce_log_close();
		exit(EXIT_FAILURE);

	case 0:
		/* Child */
		break;

	default:
		/* Parent -- Success */

		/* One main() one exit() - in this case the parent
		 * must not call atexit handlers etc */
		_exit(EXIT_SUCCESS);
	}

	/* Detach TTY */
	setsid();

	/* Close all file descriptors and redirect stdio to /dev/null */
	if ((i = getdtablesize()) == -1)
		i = 256;

	while (--i >= 0) {
		if (close(i) == -1) {
			if (retries > 10) {
				mce_log(LL_CRIT,
					"close() was interrupted more than "
					"10 times. Exiting.");
				mce_log_close();
				exit(EXIT_FAILURE);
			}

			if (errno == EINTR) {
				mce_log(LL_INFO,
					"close() was interrupted; retrying.");
				errno = 0;
				i++;
				retries++;
			} else if (errno == EBADF) {
				/* Ignore invalid file descriptors */
				errno = 0;
			} else {
				mce_log(LL_CRIT,
					"Failed to close() fd %d; %s. "
					"Exiting.",
					i + 1, g_strerror(errno));
				mce_log_close();
				exit(EXIT_FAILURE);
			}
		} else {
			retries = 0;
		}
	}

	if ((i = open("/dev/null", O_RDWR)) == -1) {
		mce_log(LL_CRIT,
			"Cannot open `/dev/null'; %s. Exiting.",
			g_strerror(errno));
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	if ((dup(i) == -1)) {
		mce_log(LL_CRIT,
			"Failed to dup() `/dev/null'; %s. Exiting.",
			g_strerror(errno));
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	if ((dup(i) == -1)) {
		mce_log(LL_CRIT,
			"Failed to dup() `/dev/null'; %s. Exiting.",
			g_strerror(errno));
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	/* Set umask */
	umask(022);

	/* Set working directory */
	if ((chdir("/tmp") == -1)) {
		mce_log(LL_CRIT,
			"Failed to chdir() to `/tmp'; %s. Exiting.",
			g_strerror(errno));
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	/* Single instance */
	if ((i = open(MCE_LOCKFILE, O_RDWR | O_CREAT, 0640)) == -1) {
		mce_log(LL_CRIT,
			"Cannot open lockfile; %s. Exiting.",
			g_strerror(errno));
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	if (lockf(i, F_TLOCK, 0) == -1) {
		mce_log(LL_CRIT, "Already running. Exiting.");
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	sprintf(str, "%d\n", getpid());
	no_error_check_write(i, str, strlen(str));
	close(i);

	/* Ignore TTY signals */
	signal(SIGTSTP, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);

	/* Ignore child terminate signal */
	signal(SIGCHLD, SIG_IGN);

EXIT:
	return 0;
}
Esempio n. 9
0
int main(int argc,char **argv)
{
  unsigned long max;
  int fd;
  int fdlock;
  msgentry *msgtable;
  subentry *subtable;
  authentry *authtable;
  dateentry *datetable;

  (void) umask(022);
  sig_pipeignore();

  getconfopt(argc,argv,options,1,0);
  if (flagsyncall)
    flagsync = 1;
  else if (flagcreate)
    flagsync = 0;
  archnum = (archnum / 100) * 100;

	/* Lock list to assure that no ezmlm-send is working on it */
	/* and that the "num" message is final */
  fdlock = lockfile("lock");
					/* get num */
  if (!getconf_ulong(&max,"num",0)
      || max == 0)
    strerr_die1x(100,MSG(ERR_EMPTY_LIST));
  (void) close(fdlock);

  if (!optto || optto > max) optto = max;

  fdlock = lockfile("archive/lock");	/* lock index */
  if (!flagcreate && !archnum) {	/* adjust archnum (from) / to */
    if (getconf_ulong(&archnum,"archnum",0))
      ++archnum;
    else
      archnum = 0;
  }

  if (archnum > optto)
    _exit(0);				/* nothing to do */

  if (mkdir("archive/threads",0755) == -1)
    if (errno != error_exist)
      strerr_die2sys(111,FATAL,MSG1(ERR_CREATE,"archive/threads"));
  if (mkdir("archive/subjects",0755) == -1)
    if (errno != error_exist)
      strerr_die2sys(111,FATAL,MSG1(ERR_CREATE,"archive/subjects"));
  if (mkdir("archive/authors",0755) == -1)
    if (errno != error_exist)
      strerr_die2sys(111,FATAL,MSG1(ERR_CREATE,"archive/authors"));

					/* do the subject threading */
  idx_mkthreads(&msgtable,&subtable,&authtable,&datetable,archnum,optto,max,0);
					/* update the index */
  write_threads(msgtable,subtable,authtable,datetable,archnum,optto);
					/* update archnum */
  if ((fd = open_trunc("archnumn")) == -1)
    strerr_die2sys(111,FATAL,MSG1(ERR_CREATE,"archnumn"));
  substdio_fdbuf(&ssnum,write,fd,numbuf,sizeof(numbuf));
  if (substdio_put(&ssnum,strnum,fmt_ulong(strnum,optto)) == -1)
     strerr_die2sys(111,FATAL,MSG1(ERR_WRITE,fnn.s));
  if (substdio_puts(&ssnum,"\n") == -1)
     strerr_die2sys(111,FATAL,MSG1(ERR_WRITE,fnn.s));
  close_proper(&ssnum,"archnum","archnumn");
  switch (flagerror) {
    case 0:
       _exit(0);				/* go bye-bye */
    case -1:
       strerr_die2x(99,WARNING,"threads entry with illegal format");
    case -2:
       strerr_die2x(99,WARNING,"thread in index, but threadfile missing");
    case -3:
       strerr_die2x(99,WARNING,"a subject file lacks subject");
    case -4:
       strerr_die2x(99,WARNING,"an author file lacks author/hash");
    case -5:
       strerr_die2x(99,WARNING,"threads entry lacks message count");
    default:
       strerr_die2x(99,WARNING,"something happened that isn't quite right");
  }
}
Esempio n. 10
0
int
mhelperPerformCommand3(AuthorizationRef authorizationRef, 
                       const char *helperPath, MAHelperCommand command,
                       void(*output_callback)(const char*, void*),
                       void *callback_data,
                       int *fdret, char **error_message)
{
  int tohelper[2], fromhelper[2];
  int childStatus;
  int written;
  pid_t pid;
  int rc;
  int sv[2];
  int ok;
  AuthorizationExternalForm extAuth;
  
restart:
    ok= 1;
  childStatus= 0;
  
  if (error_message)
    *error_message= NULL;
  
  // authref --> bytestream
  if (authorizationRef && AuthorizationMakeExternalForm(authorizationRef, &extAuth))
    return MAHelperCommandInternalError;
  
  if (pipe(tohelper) < 0)
    return MAHelperCommandInternalError;
  
  if (pipe(fromhelper) < 0)
  {
    close(tohelper[0]);
    close(tohelper[1]);
    return MAHelperCommandInternalError;
  }
  
  if (fdret)
  {
    if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sv) < 0)
    {
      close(tohelper[0]);
      close(tohelper[1]);
      close(fromhelper[0]);
      close(fromhelper[1]);
      return MAHelperCommandInternalError;
    }
  }
  
  if ((pid = fork()) < 0)
  {
    if (fdret)
    {
      close(sv[0]);
      close(sv[1]);
    }
    close(tohelper[0]);
    close(tohelper[1]);
    close(fromhelper[0]);
    close(fromhelper[1]);
    return MAHelperCommandInternalError;
  }
  else if (pid == 0)
  {
    char *const envp[] = { NULL };
    char sockfd[32];
    
    if (fdret)
    {
      sprintf(sockfd, "%i", sv[1]);
      close(sv[0]);
    }
    close(0);
    dup2(tohelper[0], 0);
    close(tohelper[0]);
    close(tohelper[1]);
    
    close(1);
    dup2(fromhelper[1], 1);
#ifndef DO_DEBUG
    close(2);
    dup2(fromhelper[1], 2);
#endif
    close(fromhelper[0]);
    close(fromhelper[1]);
    
    if (fdret)
      execle(helperPath, helperPath, sockfd, NULL, envp, NULL);
    else
      execle(helperPath, helperPath, NULL, envp, NULL);
    _exit(MAHelperCommandHelperNotFound);
  }
  signal(SIGPIPE, SIG_IGN);
  
  close(tohelper[0]);
  close(fromhelper[1]);
  if (fdret)
    close(sv[1]);
  
  DEBUG("sending auth...");
  if (write(tohelper[1], &extAuth, sizeof(extAuth)) != sizeof(extAuth))
    ok= 0;
  else
  {
    DEBUG("sending command...");
    written= write(tohelper[1], &command, sizeof(MAHelperCommand));  
    if (written != sizeof(MAHelperCommand))
      ok= 0;
  }
  DEBUG("end sending.");
  if (ok && fdret)
  {
    char buffer[1024];
    
    // helper will send an error message in case of error
    // otherwise, an empty string and the fd later
    DEBUG("reading reply code...");
    *fdret= -1;
    // read reply code 
    if (read(fromhelper[0], buffer, sizeof(buffer)) < 0)
      ok= false;
    else
    {
      DEBUG("reply from helper was '%s'", buffer);
      if (buffer[0])
      {
        if (error_message)
          *error_message= strdup(buffer);
      }
      else
      {
        DEBUG("waiting for fd from socket...");
        // read the fd from the socket to the helper
        if (read_fd(sv[0], buffer, sizeof(buffer), fdret) < 0 || *fdret < 0)
        {
        }
        // this is the file name (not error)
        buffer[sizeof(buffer)-1]= 0;
        if (error_message)
          *error_message= strdup(buffer);
        
        DEBUG("fd arrived %i (%s)", *fdret, buffer);
      }
    }
  }
  
  if (ok && output_callback) 
  {
    char line[1024];
    int count;
    DEBUG("waiting for process to finish");
    while ((rc= waitpid(pid, &childStatus, WNOHANG)) == 0)
    {
      count= read(fromhelper[0], line, sizeof(line));
      if (count > 0)
      {
        line[count]= 0;
        (*output_callback)(line, callback_data);
      }
    }
  }
  else
  {
    DEBUG("waiting for error process to finish");
    rc= waitpid(pid, &childStatus, 0);
  }
  DEBUG("end");
  close(fromhelper[0]);
  if (fdret)
    close(sv[0]);
  close(tohelper[1]);
  
  if (WEXITSTATUS(childStatus) == MAHelperCommandNeedsRestart)
    goto restart;
	
  if (!ok)
    return MAHelperCommandInternalError;
  
  if (rc < 0)
    return MAHelperCommandInternalError;
  
  if (!WIFEXITED(childStatus))
    return MAHelperCommandInternalError;
  
  return WEXITSTATUS(childStatus);
}
Esempio n. 11
0
/*
 * Runs command in a subprocess with a minimal environment.
 * Returns pid on success, 0 on failure.
 * The child stdout and stderr maybe captured, left attached or sent to
 * /dev/null depending on the contents of flags.
 * "tag" is prepended to log messages.
 * NB. "command" is only used for logging; the actual command executed is
 * av[0].
 */
pid_t
subprocess(const char *tag, struct passwd *pw, const char *command,
    int ac, char **av, FILE **child, u_int flags)
{
	FILE *f = NULL;
	struct stat st;
	int fd, devnull, p[2], i;
	pid_t pid;
	char *cp, errmsg[512];
	u_int envsize;
	char **child_env;

	if (child != NULL)
		*child = NULL;

	debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
	    tag, command, pw->pw_name, flags);

	/* Check consistency */
	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
		error("%s: inconsistent flags", __func__);
		return 0;
	}
	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
		error("%s: inconsistent flags/output", __func__);
		return 0;
	}

	/*
	 * If executing an explicit binary, then verify the it exists
	 * and appears safe-ish to execute
	 */
	if (*av[0] != '/') {
		error("%s path is not absolute", tag);
		return 0;
	}
	temporarily_use_uid(pw);
	if (stat(av[0], &st) < 0) {
		error("Could not stat %s \"%s\": %s", tag,
		    av[0], strerror(errno));
		restore_uid();
		return 0;
	}
	if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
		restore_uid();
		return 0;
	}
	/* Prepare to keep the child's stdout if requested */
	if (pipe(p) != 0) {
		error("%s: pipe: %s", tag, strerror(errno));
		restore_uid();
		return 0;
	}
	restore_uid();

	switch ((pid = fork())) {
	case -1: /* error */
		error("%s: fork: %s", tag, strerror(errno));
		close(p[0]);
		close(p[1]);
		return 0;
	case 0: /* child */
		/* Prepare a minimal environment for the child. */
		envsize = 5;
		child_env = xcalloc(sizeof(*child_env), envsize);
		child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
		child_set_env(&child_env, &envsize, "USER", pw->pw_name);
		child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
		child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
		if ((cp = getenv("LANG")) != NULL)
			child_set_env(&child_env, &envsize, "LANG", cp);

		for (i = 0; i < NSIG; i++)
			signal(i, SIG_DFL);

		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
			error("%s: open %s: %s", tag, _PATH_DEVNULL,
			    strerror(errno));
			_exit(1);
		}
		if (dup2(devnull, STDIN_FILENO) == -1) {
			error("%s: dup2: %s", tag, strerror(errno));
			_exit(1);
		}

		/* Set up stdout as requested; leave stderr in place for now. */
		fd = -1;
		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
			fd = p[1];
		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
			fd = devnull;
		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
			error("%s: dup2: %s", tag, strerror(errno));
			_exit(1);
		}
		closefrom(STDERR_FILENO + 1);

		/* Don't use permanently_set_uid() here to avoid fatal() */
		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
			    strerror(errno));
			_exit(1);
		}
		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
			    strerror(errno));
			_exit(1);
		}
		/* stdin is pointed to /dev/null at this point */
		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
			error("%s: dup2: %s", tag, strerror(errno));
			_exit(1);
		}

		execve(av[0], av, child_env);
		error("%s exec \"%s\": %s", tag, command, strerror(errno));
		_exit(127);
	default: /* parent */
		break;
	}

	close(p[1]);
	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
		close(p[0]);
	else if ((f = fdopen(p[0], "r")) == NULL) {
		error("%s: fdopen: %s", tag, strerror(errno));
		close(p[0]);
		/* Don't leave zombie child */
		kill(pid, SIGTERM);
		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
			;
		return 0;
	}
	/* Success */
	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
	if (child != NULL)
		*child = f;
	return pid;
}
Esempio n. 12
0
/*
 * Display the contents of a uio structure on a terminal.  Used by wall(1),
 * syslogd(8), and talkd(8).  Forks and finishes in child if write would block,
 * waiting up to tmout seconds.  Returns pointer to error string on unexpected
 * error; string is not newline-terminated.  Various "normal" errors are
 * ignored (exclusive-use, lack of permission, etc.).
 */
const char *
ttymsg(struct iovec *iov, int iovcnt, const char *line, int tmout)
{
	struct iovec localiov[7];
	ssize_t left, wret;
	int cnt, fd;
	static char device[MAXNAMLEN] = _PATH_DEV;
	static char errbuf[1024];
	char *p;
	int forked;

	forked = 0;
	if (iovcnt > (int)(sizeof(localiov) / sizeof(localiov[0])))
		return ("too many iov's (change code in wall/ttymsg.c)");

	p = device + sizeof(_PATH_DEV) - 1;
	strlcpy(p, line, sizeof(device));
	if (strncmp(p, "pts/", 4) == 0)
		p += 4;
	if (strchr(p, '/') != NULL) {
		/* A slash is an attempt to break security... */
		(void) snprintf(errbuf, sizeof(errbuf),
		    "Too many '/' in \"%s\"", device);
		return (errbuf);
	}

	/*
	 * open will fail on slip lines or exclusive-use lines
	 * if not running as root; not an error.
	 */
	if ((fd = open(device, O_WRONLY|O_NONBLOCK, 0)) < 0) {
		if (errno == EBUSY || errno == EACCES)
			return (NULL);
		(void) snprintf(errbuf, sizeof(errbuf), "%s: %s", device,
		    strerror(errno));
		return (errbuf);
	}

	for (cnt = 0, left = 0; cnt < iovcnt; ++cnt)
		left += iov[cnt].iov_len;

	for (;;) {
		wret = writev(fd, iov, iovcnt);
		if (wret >= left)
			break;
		if (wret >= 0) {
			left -= wret;
			if (iov != localiov) {
				bcopy(iov, localiov, 
				    iovcnt * sizeof(struct iovec));
				iov = localiov;
			}
			for (cnt = 0; (size_t)wret >= iov->iov_len; ++cnt) {
				wret -= iov->iov_len;
				++iov;
				--iovcnt;
			}
			if (wret) {
				iov->iov_base = (char *)iov->iov_base + wret;
				iov->iov_len -= wret;
			}
			continue;
		}
		if (errno == EWOULDBLOCK) {
			int cpid;

			if (forked) {
				(void) close(fd);
				_exit(1);
			}
			cpid = fork();
			if (cpid < 0) {
				(void) snprintf(errbuf, sizeof(errbuf),
				    "fork: %s", strerror(errno));
				(void) close(fd);
				return (errbuf);
			}
			if (cpid) {	/* parent */
				(void) close(fd);
				return (NULL);
			}
			forked++;
			/* wait at most tmout seconds */
			(void) signal(SIGALRM, SIG_DFL);
			(void) signal(SIGTERM, SIG_DFL); /* XXX */
			(void) sigsetmask(0);
			(void) alarm((u_int)tmout);
			(void) fcntl(fd, F_SETFL, 0);	/* clear O_NONBLOCK */
			continue;
		}
		/*
		 * We get ENODEV on a slip line if we're running as root,
		 * and EIO if the line just went away.
		 */
		if (errno == ENODEV || errno == EIO)
			break;
		(void) close(fd);
		if (forked)
			_exit(1);
		(void) snprintf(errbuf, sizeof(errbuf),
		    "%s: %s", device, strerror(errno));
		return (errbuf);
	}

	(void) close(fd);
	if (forked)
		_exit(0);
	return (NULL);
}
    bool initializeServerGlobalState(bool isMongodShutdownSpecialCase) {

        Listener::globalTicketHolder.resize( cmdLine.maxConns );

#ifndef _WIN32
        if (!fs::is_directory(cmdLine.socket)) {
            cout << cmdLine.socket << " must be a directory" << endl;
            return false;
        }

        if (cmdLine.doFork) {
            fassert(16447, !cmdLine.logpath.empty() || cmdLine.logWithSyslog);

            cout.flush();
            cerr.flush();

            cmdLine.parentProc = getpid();

            // facilitate clean exit when child starts successfully
            setupLaunchSignals();

            cout << "about to fork child process, waiting until server is ready for connections."
                 << endl;

            pid_t child1 = fork();
            if (child1 == -1) {
                cout << "ERROR: stage 1 fork() failed: " << errnoWithDescription();
                _exit(EXIT_ABRUPT);
            }
            else if (child1) {
                // this is run in the original parent process
                int pstat;
                waitpid(child1, &pstat, 0);

                if (WIFEXITED(pstat)) {
                    if (WEXITSTATUS(pstat)) {
                        cout << "ERROR: child process failed, exited with error number "
                             << WEXITSTATUS(pstat) << endl;
                    }
                    else {
                        cout << "child process started successfully, parent exiting" << endl;
                    }

                    _exit(WEXITSTATUS(pstat));
                }

                _exit(50);
            }

            if ( chdir("/") < 0 ) {
                cout << "Cant chdir() while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }
            setsid();

            cmdLine.leaderProc = getpid();

            pid_t child2 = fork();
            if (child2 == -1) {
                cout << "ERROR: stage 2 fork() failed: " << errnoWithDescription();
                _exit(EXIT_ABRUPT);
            }
            else if (child2) {
                // this is run in the middle process
                int pstat;
                cout << "forked process: " << child2 << endl;
                waitpid(child2, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(51);
            }

            // this is run in the final child process (the server)

            // stdout handled in initLogging
            //fclose(stdout);
            //freopen("/dev/null", "w", stdout);

            fclose(stderr);
            fclose(stdin);

            FILE* f = freopen("/dev/null", "w", stderr);
            if ( f == NULL ) {
                cout << "Cant reassign stderr while forking server process: " << strerror(errno) << endl;
                return false;
            }

            f = freopen("/dev/null", "r", stdin);
            if ( f == NULL ) {
                cout << "Cant reassign stdin while forking server process: " << strerror(errno) << endl;
                return false;
            }

            setupCoreSignals();
            setupSignals( true );
        }

        if (cmdLine.logWithSyslog) {
            StringBuilder sb;
            sb << cmdLine.binaryName << "." << cmdLine.port;
            Logstream::useSyslog( sb.str().c_str() );
        }
#endif
        if (!cmdLine.logpath.empty() && !isMongodShutdownSpecialCase) {
            fassert(16448, !cmdLine.logWithSyslog);
            string absoluteLogpath = boost::filesystem::absolute(
                    cmdLine.logpath, cmdLine.cwd).string();
            if (!initLogging(absoluteLogpath, cmdLine.logAppend)) {
                cout << "Bad logpath value: \"" << absoluteLogpath << "\"; terminating." << endl;
                return false;
            }
        }

        if (!cmdLine.pidFile.empty()) {
            writePidFile(cmdLine.pidFile);
        }

        if (!cmdLine.keyFile.empty()) {

            if (!setUpSecurityKey(cmdLine.keyFile)) {
                // error message printed in setUpPrivateKey
                return false;
            }

            noauth = false;
        }

#ifdef MONGO_SSL
        if (cmdLine.sslOnNormalPorts) {

            if ( cmdLine.sslPEMKeyFile.size() == 0 ) {
                log() << "need sslPEMKeyFile" << endl;
                return false;
            }

            cmdLine.sslServerManager = new SSLManager( false );
            if ( ! cmdLine.sslServerManager->setupPEM( cmdLine.sslPEMKeyFile , cmdLine.sslPEMKeyPassword ) ) {
                return false;
            }
        }
        else if ( cmdLine.sslPEMKeyFile.size() || cmdLine.sslPEMKeyPassword.size() ) {
            log() << "need to enable sslOnNormalPorts" << endl;
            return false;
        }
#endif

        return true;
    }
Esempio n. 14
0
void tty_sigreset(int i)
{
  tty_reset();
  _exit(128+i);
}
Esempio n. 15
0
result_t *
sandbox_execute(sandbox_t * psbox)
{
    FUNC_BEGIN("sandbox_execute(%p)", psbox);

    assert(psbox);

    if (psbox == NULL)
    {
        WARNING("psbox: bad pointer");
        FUNC_RET(NULL, "sandbox_execute()");
    }

    if (!sandbox_check(psbox))
    {
        WARNING("sandbox pre-execution state check failed");
        FUNC_RET(&psbox->result, "sandbox_execute()");
    }

#ifdef WITH_CUSTOM_MONITOR
    pthread_t tid;

    if (pthread_create(&tid, NULL, psbox->ctrl.monitor, (void *)psbox) != 0)
    {
        WARNING("failed creating the monitor thread");
        FUNC_RET(&psbox->result, "sandbox_execute()");
    }
    DBG("created the monitor thread");
#endif /* WITH_CUSTOM_MONITOR */

    /* Fork the prisoner process */
    psbox->ctrl.pid = fork();

    /* Execute the prisoner program */
    if (psbox->ctrl.pid == 0)
    {
        DBG("entering: the prisoner program");
        /* Start executing the prisoner program */
        _exit(__sandbox_task_execute(&psbox->task));
    }
    else
    {
        DBG("target program forked as pid %d", psbox->ctrl.pid);
        /* Start executing the tracing thread */
        psbox->ctrl.tracer(psbox);
    }

#ifdef WITH_CUSTOM_MONITOR
    if (pthread_join(tid, NULL) != 0)
    {
        WARNING("failed joining the monitor thread");
        if (pthread_cancel(tid) != 0)
        {
            WARNING("failed canceling the monitor thread");
            FUNC_RET(NULL, "sandbox_execute()");
        }
    }
    DBG("joined the monitor thread");
#endif /* WITH_CUSTOM_MONITOR */

    FUNC_RET(&psbox->result, "sandbox_execute()");
}
Esempio n. 16
0
extern "C" int32_t ForkAndExecProcess(const char* filename,
                                      char* const argv[],
                                      char* const envp[],
                                      const char* cwd,
                                      int32_t redirectStdin,
                                      int32_t redirectStdout,
                                      int32_t redirectStderr,
                                      int32_t* childPid,
                                      int32_t* stdinFd,
                                      int32_t* stdoutFd,
                                      int32_t* stderrFd)
{
    int success = true;
    int stdinFds[2] = {-1, -1}, stdoutFds[2] = {-1, -1}, stderrFds[2] = {-1, -1};
    int processId = -1;

    // Validate arguments
    if (nullptr == filename || nullptr == argv || nullptr == envp || nullptr == stdinFd || nullptr == stdoutFd ||
        nullptr == stderrFd || nullptr == childPid)
    {
        assert(false && "null argument.");
        errno = EINVAL;
        success = false;
        goto done;
    }

    if ((redirectStdin & ~1) != 0 || (redirectStdout & ~1) != 0 || (redirectStderr & ~1) != 0)
    {
        assert(false && "Boolean redirect* inputs must be 0 or 1.");
        errno = EINVAL;
        success = false;
        goto done;
    }

    // Open pipes for any requests to redirect stdin/stdout/stderr
    if ((redirectStdin && pipe(stdinFds) != 0) || (redirectStdout && pipe(stdoutFds) != 0) ||
        (redirectStderr && pipe(stderrFds) != 0))
    {
        assert(false && "pipe() failed.");
        success = false;
        goto done;
    }

    // Fork the child process
    if ((processId = fork()) == -1)
    {
        assert(false && "fork() failed.");
        success = false;
        goto done;
    }

    if (processId == 0) // processId == 0 if this is child process
    {
        // Close the child's copy of the parent end of any open pipes
        CloseIfOpen(stdinFds[WRITE_END_OF_PIPE]);
        CloseIfOpen(stdoutFds[READ_END_OF_PIPE]);
        CloseIfOpen(stderrFds[READ_END_OF_PIPE]);

        // For any redirections that should happen, dup the pipe descriptors onto stdin/out/err.
        // Then close out the old pipe descriptrs, which we no longer need.
        if ((redirectStdin && dup2(stdinFds[READ_END_OF_PIPE], STDIN_FILENO) == -1) ||
            (redirectStdout && dup2(stdoutFds[WRITE_END_OF_PIPE], STDOUT_FILENO) == -1) ||
            (redirectStderr && dup2(stderrFds[WRITE_END_OF_PIPE], STDERR_FILENO) == -1))
        {
            _exit(errno != 0 ? errno : EXIT_FAILURE);
        }
        CloseIfOpen(stdinFds[READ_END_OF_PIPE]);
        CloseIfOpen(stdoutFds[WRITE_END_OF_PIPE]);
        CloseIfOpen(stderrFds[WRITE_END_OF_PIPE]);

        // Change to the designated working directory, if one was specified
        if (nullptr != cwd && chdir(cwd) == -1)
        {
            _exit(errno != 0 ? errno : EXIT_FAILURE);
        }

        // Finally, execute the new process.  execve will not return if it's successful.
        execve(filename, argv, envp);
        _exit(errno != 0 ? errno : EXIT_FAILURE); // execve failed
    }

    // This is the parent process. processId == pid of the child
    *childPid = processId;
    *stdinFd = stdinFds[WRITE_END_OF_PIPE];
    *stdoutFd = stdoutFds[READ_END_OF_PIPE];
    *stderrFd = stderrFds[READ_END_OF_PIPE];

done:
    // Regardless of success or failure, close the parent's copy of the child's end of
    // any opened pipes.  The parent doesn't need them anymore.
    CloseIfOpen(stdinFds[READ_END_OF_PIPE]);
    CloseIfOpen(stdoutFds[WRITE_END_OF_PIPE]);
    CloseIfOpen(stderrFds[WRITE_END_OF_PIPE]);

    // If we failed, close everything else and give back error values in all out arguments.
    if (!success)
    {
        CloseIfOpen(stdinFds[WRITE_END_OF_PIPE]);
        CloseIfOpen(stdoutFds[READ_END_OF_PIPE]);
        CloseIfOpen(stderrFds[READ_END_OF_PIPE]);

        *stdinFd = -1;
        *stdoutFd = -1;
        *stderrFd = -1;
        *childPid = -1;
    }

    return success ? 0 : -1;
}
Esempio n. 17
0
//............................................................................
void Q_onAssert(char const Q_ROM * const file, int line) {
    fprintf(stderr, "Assertion failed in %s, line %d", file, line);
    _exit(-1);
}
Esempio n. 18
0
FILE *
spopen (const char *cmdstring)
{
	char *env[2];
	char *cmd = NULL;
	char **argv = NULL;
	char *str, *tmp;
	int argc;

	int i = 0, pfd[2], pfderr[2];
	pid_t pid;

#ifdef 	RLIMIT_CORE
	/* do not leave core files */
	struct rlimit limit;
	getrlimit (RLIMIT_CORE, &limit);
	limit.rlim_cur = 0;
	setrlimit (RLIMIT_CORE, &limit);
#endif

	env[0] = strdup("LC_ALL=C");
	env[1] = '\0';

	/* if no command was passed, return with no error */
	if (cmdstring == NULL)
		return (NULL);

	/* make copy of command string so strtok() doesn't silently modify it */
	/* (the calling program may want to access it later) */
	cmd = malloc (strlen (cmdstring) + 1);
	if (cmd == NULL)
		return NULL;
	strcpy (cmd, cmdstring);

	/* This is not a shell, so we don't handle "???" */
	if (strstr (cmdstring, "\""))
		return NULL;

	/* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
	if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
		return NULL;

	/* there cannot be more args than characters */
	argc = strlen (cmdstring) + 1;	/* add 1 for NULL termination */
	argv = malloc (sizeof(char*)*argc);

	if (argv == NULL) {
		printf ("%s\n", _("Could not malloc argv array in popen()"));
		return NULL;
	}

	/* loop to get arguments to command */
	while (cmd) {
		str = cmd;
		str += strspn (str, " \t\r\n");	/* trim any leading whitespace */

		if (i >= argc - 2) {
			printf ("%s\n",_("CRITICAL - You need more args!!!"));
			return (NULL);
		}

		if (strstr (str, "'") == str) {	/* handle SIMPLE quoted strings */
			str++;
			if (!strstr (str, "'"))
				return NULL;						/* balanced? */
			cmd = 1 + strstr (str, "'");
			str[strcspn (str, "'")] = 0;
		}
		else if (strcspn(str,"'") < strcspn (str, " \t\r\n")) {
										/* handle --option='foo bar' strings */
			tmp = str + strcspn(str, "'") + 1;
			if (!strstr (tmp, "'"))
				return NULL;						/* balanced? */
			tmp += strcspn(tmp,"'") + 1;
			*tmp = 0;
			cmd = tmp + 1;
		} else {
			if (strpbrk (str, " \t\r\n")) {
				cmd = 1 + strpbrk (str, " \t\r\n");
				str[strcspn (str, " \t\r\n")] = 0;
			}
			else {
				cmd = NULL;
			}
		}

		if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
			cmd = NULL;

		argv[i++] = str;

	}
	argv[i] = NULL;

	if (childpid == NULL) {				/* first time through */
		maxfd = open_max ();				/* allocate zeroed out array for child pids */
		if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
			return (NULL);
	}

	if (child_stderr_array == NULL) {	/* first time through */
		maxfd = open_max ();				/* allocate zeroed out array for child pids */
		if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
			return (NULL);
	}

	if (pipe (pfd) < 0)
		return (NULL);							/* errno set by pipe() */

	if (pipe (pfderr) < 0)
		return (NULL);							/* errno set by pipe() */

#ifdef REDHAT_SPOPEN_ERROR
	if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
		usage4 (_("Cannot catch SIGCHLD"));
	}
#endif

	if ((pid = fork ()) < 0)
		return (NULL);							/* errno set by fork() */
	else if (pid == 0) {					/* child */
		close (pfd[0]);
		if (pfd[1] != STDOUT_FILENO) {
			dup2 (pfd[1], STDOUT_FILENO);
			close (pfd[1]);
		}
		close (pfderr[0]);
		if (pfderr[1] != STDERR_FILENO) {
			dup2 (pfderr[1], STDERR_FILENO);
			close (pfderr[1]);
		}
		/* close all descriptors in childpid[] */
		for (i = 0; i < maxfd; i++)
			if (childpid[i] > 0)
				close (i);

		execve (argv[0], argv, env);
		_exit (0);
	}

	close (pfd[1]);								/* parent */
	if ((child_process = fdopen (pfd[0], "r")) == NULL)
		return (NULL);
	close (pfderr[1]);

	childpid[fileno (child_process)] = pid;	/* remember child pid for this fd */
	child_stderr_array[fileno (child_process)] = pfderr[0];	/* remember STDERR */
	return (child_process);
}
Esempio n. 19
0
BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags,
		LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
		LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
		LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
	pid_t pid;
	int flags;
	int numArgs;
	LPSTR* pArgs = NULL;
	char** envp = NULL;
	char* filename = NULL;
	HANDLE thread;
	HANDLE process;
	WINPR_ACCESS_TOKEN* token;
	LPTCH lpszEnvironmentBlock;
	BOOL ret = FALSE;
	sigset_t oldSigMask;
	sigset_t newSigMask;
	BOOL restoreSigMask = FALSE;

	pid = 0;
	numArgs = 0;
	lpszEnvironmentBlock = NULL;

	pArgs = CommandLineToArgvA(lpCommandLine, &numArgs);
	if (!pArgs)
		return FALSE;

	flags = 0;

	token = (WINPR_ACCESS_TOKEN*) hToken;

	if (lpEnvironment)
	{
		envp = EnvironmentBlockToEnvpA(lpEnvironment);
	}
	else
	{
		lpszEnvironmentBlock = GetEnvironmentStrings();
		if (!lpszEnvironmentBlock)
			goto finish;
		envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock);
	}
	if (!envp)
		goto finish;

	filename = FindApplicationPath(pArgs[0]);
	if (NULL == filename)
		goto finish;

	/* block all signals so that the child can safely reset the caller's handlers */
	sigfillset(&newSigMask);
	restoreSigMask = !pthread_sigmask(SIG_SETMASK, &newSigMask, &oldSigMask);

	/* fork and exec */

	pid = fork();

	if (pid < 0)
	{
		/* fork failure */
		goto finish;
	}

	if (pid == 0)
	{
		/* child process */
#ifndef __sun
		int maxfd;
#endif
		int fd;
		int sig;
		sigset_t set;
		struct sigaction act;

		/* set default signal handlers */
		memset(&act, 0, sizeof(act));
		act.sa_handler = SIG_DFL;
		act.sa_flags = 0;
		sigemptyset(&act.sa_mask);
		for (sig = 1; sig < NSIG; sig++)
			sigaction(sig, &act, NULL);
		/* unblock all signals */
		sigfillset(&set);
		pthread_sigmask(SIG_UNBLOCK, &set, NULL);

		if (lpStartupInfo)
		{
			int handle_fd;

			handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdOutput);
			if (handle_fd != -1)
				dup2(handle_fd, STDOUT_FILENO);

			handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdError);
			if (handle_fd != -1)
				dup2(handle_fd, STDERR_FILENO);

			handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdInput);
			if (handle_fd != -1)
				dup2(handle_fd, STDIN_FILENO);
		}


#ifdef __sun
		closefrom(3);
#else
#ifdef F_MAXFD // on some BSD derivates
		maxfd = fcntl(0, F_MAXFD);
#else
		maxfd = sysconf(_SC_OPEN_MAX);
#endif
		for(fd=3; fd<maxfd; fd++)
			close(fd);
#endif // __sun

		if (token)
		{
			if (token->GroupId)
			{
				int rc = setgid((gid_t) token->GroupId);
				if (rc < 0)
				{
				}
				else
				{
					initgroups(token->Username, (gid_t) token->GroupId);
				}
			}

			if (token->UserId)
				setuid((uid_t) token->UserId);

		}

		/* TODO: add better cwd handling and error checking */
		if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0)
			chdir(lpCurrentDirectory);

		if (execve(filename, pArgs, envp) < 0)
		{
			/* execve failed - end the process */
			_exit(1);
		}
	}
	else
	{
		/* parent process */
	}

	process = CreateProcessHandle(pid);

	if (!process)
	{
		goto finish;
	}

	thread = CreateNoneHandle();

	if (!thread)
	{
		ProcessHandleCloseHandle(process);
		goto finish;
	}

	lpProcessInformation->hProcess = process;
	lpProcessInformation->hThread = thread;
	lpProcessInformation->dwProcessId = (DWORD) pid;
	lpProcessInformation->dwThreadId = (DWORD) pid;

	ret = TRUE;

finish:

	/* restore caller's original signal mask */
	if (restoreSigMask)
		pthread_sigmask(SIG_SETMASK, &oldSigMask, NULL);


	free(filename);

	if (pArgs)
	{
		HeapFree(GetProcessHeap(), 0, pArgs);
	}

	if (lpszEnvironmentBlock)
		FreeEnvironmentStrings(lpszEnvironmentBlock);

	if (envp)
	{
		int i = 0;

		while (envp[i])
		{
			free(envp[i]);
			i++;
		}

		free(envp);
	}

	return ret;
}
Esempio n. 20
0
/**
 *  Find the short option descriptor for the current option
 *
 * @param pOpts      option data
 * @param optValue   option flag character
 * @param pOptState  state about current option
 */
LOCAL tSuccess
opt_find_short(tOptions* pOpts, uint_t optValue, tOptState* pOptState)
{
    tOptDesc*  pRes = pOpts->pOptDesc;
    int        ct   = pOpts->optCt;

    /*
     *  Search the option list
     */
    do  {
        if (optValue != pRes->optValue)
            continue;

        if (SKIP_OPT(pRes)) {
            if (  (pRes->fOptState == (OPTST_OMITTED | OPTST_NO_INIT))
               && (pRes->pz_Name != NULL)) {
                if ((pOpts->fOptSet & OPTPROC_ERRSTOP) == 0)
                    return FAILURE;
        
                fprintf(stderr, zDisabledErr, pOpts->pzProgPath, pRes->pz_Name);
                if (pRes->pzText != NULL)
                    fprintf(stderr, SET_OFF_FMT, pRes->pzText);
                fputc(NL, stderr);
                (*pOpts->pUsageProc)(pOpts, EXIT_FAILURE);
                /* NOTREACHED */
                _exit(EXIT_FAILURE); /* to be certain */
            }
            goto short_opt_error;
        }

        pOptState->pOD     = pRes;
        pOptState->optType = TOPT_SHORT;
        return SUCCESS;

    } while (pRes++, --ct > 0);

    /*
     *  IF    the character value is a digit
     *    AND there is a special number option ("-n")
     *  THEN the result is the "option" itself and the
     *       option is the specially marked "number" option.
     */
    if (  IS_DEC_DIGIT_CHAR(optValue)
       && (pOpts->specOptIdx.number_option != NO_EQUIVALENT) ) {
        pOptState->pOD = \
        pRes           = pOpts->pOptDesc + pOpts->specOptIdx.number_option;
        (pOpts->pzCurOpt)--;
        pOptState->optType = TOPT_SHORT;
        return SUCCESS;
    }

 short_opt_error:

    /*
     *  IF we are to stop on errors (the default, actually)
     *  THEN call the usage procedure.
     */
    if ((pOpts->fOptSet & OPTPROC_ERRSTOP) != 0) {
        fprintf(stderr, zIllOptChr, pOpts->pzProgPath, optValue);
        (*pOpts->pUsageProc)(pOpts, EXIT_FAILURE);
        /* NOTREACHED */
        _exit(EXIT_FAILURE); /* to be certain */
    }

    return FAILURE;
}
Esempio n. 21
0
gboolean 
mdm_display_manage (MdmDisplay *d)
{
    pid_t pid;
    int fds[2];

    if (!d) 
	return FALSE;

    mdm_debug ("mdm_display_manage: Managing %s", d->name);

    if (pipe (fds) < 0) {
	    mdm_error ("mdm_display_manage: Cannot create pipe");
    }

    if ( ! mdm_display_check_loop (d))
	    return FALSE;

    if (d->slavepid != 0)
	    mdm_debug ("mdm_display_manage: Old slave pid is %d", (int)d->slavepid);

    /* If we have an old slave process hanging around, kill it */
    /* This shouldn't be a normal code path however, so it doesn't matter
     * that we are hanging */
    whack_old_slave (d, FALSE /* kill_connection */);

    /* Ensure that /tmp/.ICE-unix and /tmp/.X11-unix exist and have the
     * correct permissions */
    mdm_ensure_sanity ();

    d->managetime = time (NULL);

    mdm_debug ("Forking slave process");

    /* Fork slave process */
    pid = d->slavepid = fork ();

    switch (pid) {

    case 0:

	setpgid (0, 0);

	/* Make the slave it's own leader.  This 1) makes killing -pid of
	 * the daemon work more sanely because the daemon can whack the
	 * slave much better itself */
	setsid ();

	/* In the child setup empty mask and set all signals to
	 * default values, we'll make them more fun later */
	mdm_unset_signals ();

	d->slavepid = getpid ();
	
	mdm_connection_close (pipeconn);
	pipeconn = NULL;
	mdm_connection_close (unixconn);
	unixconn = NULL;

	mdm_log_shutdown ();

	/* Debian changes */
#if 0
	/* upstream version */
-	/* Close everything */
-	mdm_close_all_descriptors (0 /* from */, fds[0] /* except */, slave_fifo_pipe_fd /* except2 */);
#endif
	/* Close stdin/stdout/stderr.  Leave others, as pam modules may have them open */
	VE_IGNORE_EINTR (close (0));
	VE_IGNORE_EINTR (close (1));
	VE_IGNORE_EINTR (close (2));
	/* End of Debian changes */

	/* No error checking here - if it's messed the best response
         * is to ignore & try to continue */
	mdm_open_dev_null (O_RDONLY); /* open stdin - fd 0 */
	mdm_open_dev_null (O_RDWR); /* open stdout - fd 1 */
	mdm_open_dev_null (O_RDWR); /* open stderr - fd 2 */

	mdm_log_init ();

	d->slave_notify_fd = fds[0];

	fcntl (d->slave_notify_fd, F_SETFL, fcntl (d->slave_notify_fd, F_GETFL) | O_NONBLOCK);

	mdm_slave_start (d);
	/* should never retern */

	/* yaikes, how did we ever get here? */
	mdm_server_stop (d);
	_exit (DISPLAY_REMANAGE);

	break;

    case -1:
	d->slavepid = 0;
	mdm_error ("mdm_display_manage: Failed forking MDM slave process for %s", d->name);

	return FALSE;

    default:
	mdm_debug ("mdm_display_manage: Forked slave: %d", (int)pid);
	d->master_notify_fd = fds[1];
	VE_IGNORE_EINTR (close (fds[0]));
	break;
    }

    /* invalidate chosen hostname */
    g_free (d->chosen_hostname);
    d->chosen_hostname = NULL;

    /* use_chooser can only be temporary, if you want it permanent you set it
       up in the server definition with "chooser=true" and it will get set up
       during server command line resolution */
    d->use_chooser = FALSE;

    if (SERVER_IS_LOCAL (d)) {
	    d->dispstat = DISPLAY_ALIVE;
    }

    /* reset sleep to 1, to sleep just in case (avoids X server races) */
    d->sleep_before_run = 1;

    return TRUE;
}
Esempio n. 22
0
void abort(void)
{
	_exit(1);
}
Esempio n. 23
0
static void 
traphandler(int sig, siginfo_t *si, void *UC)
{
  ucontext_t *uc = UC;

  if(extra_traphandler != NULL && !extra_traphandler(sig, si, UC))
    return;
    
  static void *frames[MAXFRAMES];
  char buf[256];
  int nframes = backtrace(frames, MAXFRAMES);
  const char *reason = NULL;

  TRAPMSG("Signal: %d in %s ", sig, line1);

  switch(sig) {
  case SIGSEGV:
    switch(si->si_code) {
    case SEGV_MAPERR:  reason = "Address not mapped"; break;
    case SEGV_ACCERR:  reason = "Access error"; break;
    }
    break;

  case SIGFPE:
    switch(si->si_code) {
    case FPE_INTDIV:  reason = "Integer division by zero"; break;
    }
    break;
  }

  addr2text(buf, sizeof(buf), si->si_addr);

  TRAPMSG("Fault address %s (%s)", buf, reason ?: "N/A");

  TRAPMSG("Loaded libraries: %s ", libs);

#if defined(__arm__) 
  TRAPMSG("   trap_no = %08lx", uc->uc_mcontext.trap_no);
  TRAPMSG("error_code = %08lx", uc->uc_mcontext.error_code);
  TRAPMSG("   oldmask = %08lx", uc->uc_mcontext.oldmask);
  TRAPMSG("        R0 = %08lx", uc->uc_mcontext.arm_r0);
  TRAPMSG("        R1 = %08lx", uc->uc_mcontext.arm_r1);
  TRAPMSG("        R2 = %08lx", uc->uc_mcontext.arm_r2);
  TRAPMSG("        R3 = %08lx", uc->uc_mcontext.arm_r3);
  TRAPMSG("        R4 = %08lx", uc->uc_mcontext.arm_r4);
  TRAPMSG("        R5 = %08lx", uc->uc_mcontext.arm_r5);
  TRAPMSG("        R6 = %08lx", uc->uc_mcontext.arm_r6);
  TRAPMSG("        R7 = %08lx", uc->uc_mcontext.arm_r7);
  TRAPMSG("        R8 = %08lx", uc->uc_mcontext.arm_r8);
  TRAPMSG("        R9 = %08lx", uc->uc_mcontext.arm_r9);
  TRAPMSG("       R10 = %08lx", uc->uc_mcontext.arm_r10);
  TRAPMSG("        FP = %08lx", uc->uc_mcontext.arm_fp);
  TRAPMSG("        IP = %08lx", uc->uc_mcontext.arm_ip);
  TRAPMSG("        SP = %08lx", uc->uc_mcontext.arm_sp);
  TRAPMSG("        LR = %08lx", uc->uc_mcontext.arm_lr);
  TRAPMSG("        PC = %08lx", uc->uc_mcontext.arm_pc);
  TRAPMSG("      CPSR = %08lx", uc->uc_mcontext.arm_cpsr);
  TRAPMSG("fault_addr = %08lx", uc->uc_mcontext.fault_address);

#else
  char tmpbuf[1024];
  snprintf(tmpbuf, sizeof(tmpbuf), "Register dump [%d]: ", NGREG);
  int i;
  for(i = 0; i < NGREG; i++) {
#if __WORDSIZE == 64
    sappend(tmpbuf, sizeof(tmpbuf), "%016llx ", uc->uc_mcontext.gregs[i]);
#else
    sappend(tmpbuf, sizeof(tmpbuf), "%08x ", uc->uc_mcontext.gregs[i]);
#endif
  }
  TRAPMSG("%s", tmpbuf);
#endif

  dumpstack(frames, nframes);
  _exit(8);
}
Esempio n. 24
0
File: main.cpp Progetto: CCJY/coliru
int szstart()
{
    char* msg = "No main here\n";
    write(1, msg, strlen(msg));
    _exit(0);
}
Esempio n. 25
0
void command_line(int argc, char *argv[])
{
    int picNum;
    int i = 0;
    struct Image *im;
    FILE *fp;

    if (strcmp(argv[1], "-h") == 0) {
	command_usage();
    }
    i = 1;
    while (i < argc) {
	switch (argv[i][1]) {
	case 'n':
	    fprintf(stdout, "%i\n", Camera->ops->number_of_pictures());
	    break;
	case 'l':
	    if (argv[i + 1]) {
		if ((im = Camera->ops->get_preview()) == 0)
		    fprintf(stdout, "ERROR: could not get image.\n");
		else if ((fp = fopen(argv[i + 1], "w"))) {
		    fwrite(im->image,
			   (size_t) sizeof(char),
			   (size_t) im->image_size, fp);
		    fclose(fp);
		} else
		    fprintf(stdout, "ERROR: could not save image.\n");
	    } else {
		fprintf(stdout, "ERROR: 'filename' not specified.\n");
		command_usage();
	    }
	    i += 1;
	    break;
	case 's':
	    if (argv[i + 1] && argv[i + 2]) {
		fprintf(stdout,
			"Saving image %i from camera as %s: ",
			atoi(argv[i + 1]), argv[i + 2]);
		fflush(stdout);
		if (
		    ((im
		      =
		      Camera->ops->get_picture(atoi(argv[i + 1]),
					      0)) == 0))
		      fprintf(stdout, "ERROR: could not get image.\n");
		else if ((fp = fopen(argv[i + 2], "w"))) {
		    fwrite(im->image,
			   (size_t) sizeof(char),
			   (size_t) im->image_size, fp);
		    fclose(fp);
		} else {
		    fprintf(stdout, "ERROR: could not save image.\n");
		    return;
		}
	    } else {
		fprintf(stdout,
			"ERROR: '#' and 'filename' not specified.\n");
		command_usage();
	    }
	    fprintf(stdout, "\n");
	    fflush(stdout);
	    i += 2;
	    break;
	case 't':
	    if (argv[i + 1] && argv[i + 2]) {
		fprintf(stdout,
			"Saving thumbnail image %i from camera as %s: ",
			atoi(argv[i + 1]), argv[i + 2]);
		fflush(stdout);
		if (
		    (im =
		     Camera->ops->get_picture(atoi(argv[i + 1]),
					     1)) == 0)
		   fprintf(stdout, "ERROR: could not get image.\n");
		else if ((fp = fopen(argv[i + 2], "w"))) {
		    fwrite(im->image,
			   (size_t) sizeof(char),
			   (size_t) im->image_size, fp);
		    fclose(fp);
		} else {
		    fprintf(stdout, "ERROR: could not save image.\n");
		    return;
		}
	    } else {
		fprintf(stdout,
			"ERROR: '#' and 'filename' not specified.\n");
		command_usage();
	    }
	    fprintf(stdout, "\n");
	    i += 2;
	    break;
	case 'd':
	    if (argv[i + 1]) {
		if ((Camera->ops->delete_picture(atoi(argv[i + 1]))
		     == 0)) {
		    fprintf(stdout, "Could not delete image.\n");
		    return;
		} else {
		    fprintf(stdout,
			    "Deleted image %i from camera.\n",
			    atoi(argv[i + 1]));
		}
	    } else {
		fprintf(stdout, "ERROR: '#' not specified.\n");
		command_usage();
	    }
	    i += 1;
	    break;
	case 'p':
	    if (!argv[i + 1]) {
		fprintf(stdout, "ERROR: filename not specified.\n");
		command_usage();
	    } else {
		fprintf(stdout, "Taking picture...\n");

		picNum = Camera->ops->take_picture();

		if (picNum == 0) {
		    fprintf(stdout,
			    "ERROR: could not take the picture.\n");
		    return;
		} else {
		    fprintf(stdout,
			    "Saving the new image (# %i) as %s: ",
			    picNum, argv[i + 1]);
		}

		if (((im = Camera->ops->get_picture(picNum, 0)) == 0)) {
		    fprintf(stdout, "\nERROR: could not get image.\n");
		    return;
		} else {
		    if ((fp = fopen(argv[i + 1], "w"))) {
			fwrite(im->image, (size_t)
			       sizeof(char), (size_t) im->image_size, fp);
			fclose(fp);
		    } else {
			fprintf(stdout, "ERROR: could not save image.\n");
			return;
		    }
		}
	    }
	    fprintf(stdout, "\n");
	    fflush(stdout);
	    break;
	case 'c':
	    camera_summary();
	    break;
	default:
	    break;
	}
	i++;
    }
    fflush(stdout);
    _exit(0);
}
Esempio n. 26
0
void abort(void) {
	vfs_console_write(NULL, 0, "Abort called.\n", sizeof ("Abort called.\n") - 1);
	_exit(1);
}
Esempio n. 27
0
int
main(int ac, char **av)
{
	int lc;			/* loop counter */
	char *msg;		/* message returned from parse_opts */
	char *file_name;	/* testfile name */
	char *test_desc;	/* test specific error message */
	int ind;		/* counter to test different test conditions */
	int pid;
    
	/* Parse standard options given to run the test. */
	msg = parse_opts(ac, av, (option_t *) NULL, NULL);
	if (msg != (char *) NULL) {
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
		tst_exit();
	}

	/* Perform global setup for test */
	setup();

	/* set the expected errnos... */
	TEST_EXP_ENOS(exp_enos);

	pid = FORK_OR_VFORK();

	if (pid == -1) {
		tst_brkm(TBROK, cleanup, "fork() failed");
		/*NOTREACHED*/
	} else if (pid == 0) {
		if ((ltpuser = getpwnam(LTPUSER1)) == NULL) {
			tst_brkm(TBROK,cleanup,"%s not found in /etc/passwd",
				LTPUSER1);
			/*NOTREACHED*/
		}

		/* get uid of user */
		user_uid = ltpuser->pw_uid;

		seteuid(user_uid);

		/* Check looping state if -i option given */
		for (lc = 0; TEST_LOOPING(lc); lc++) {
			/* Reset Tst_count in case we are looping. */
			Tst_count=0;

			for (ind = 0; Test_cases[ind].desc != NULL; ind++) {
				file_name = Test_cases[ind].pathname;
				test_desc = Test_cases[ind].desc;

				/*
				 * Call utime(2) to test different test
				 * conditions. Verify that it fails with -1
				 * return value and sets appropriate errno.
				 */
				TEST(utime(file_name, NULL));

				/* Check return code from utime(2) */
				if (TEST_RETURN == -1) {
					TEST_ERROR_LOG(TEST_ERRNO);
					if (TEST_ERRNO ==
						Test_cases[ind].exp_errno) {
						tst_resm(TPASS, "utime() "
							"fails, %s, errno:%d",
							test_desc, TEST_ERRNO);
					} else {
						tst_resm(TFAIL, "utime(2) "
							"fails, %s, errno:%d, "
							"expected errno:%d",
							test_desc, TEST_ERRNO,
							Test_cases[ind].exp_errno);
					}
				} else {
					tst_resm(TFAIL, "utime(2) returned %d, "
						"expected -1, errno:%d",
						TEST_RETURN,
						Test_cases[ind].exp_errno);
				}
			}	/* End of TEST CASE LOOPING. */

			Tst_count++;		/* incr TEST_LOOP counter */

		}	/* End for TEST_LOOPING */
	} else {
		waitpid(pid, &status, 0);
		_exit(0);       /*
				 * Exit here and let the child clean up.
				 * This allows the errno information set
				 * by the TEST_ERROR_LOG macro and the
				 * PASS/FAIL status to be preserved for
				 * use during cleanup.
				 */
	}
	/* Call cleanup() to undo setup done for the test. */
	cleanup();
	/*NOTREACHED*/


  return(0);

}	/* End main */
Esempio n. 28
0
void sighandler(int sig)
{
	write(1, "timeout\n", 8);
	_exit(1);
}
Esempio n. 29
0
/* These are FreeRTOS hooks for various life situations. */
void vApplicationMallocFailedHook() {
  cc3200_leds(RED, ON);
  fprintf(stderr, "malloc failed\n");
  _exit(123);
}
Esempio n. 30
0
static void
execute_command_line (const char *command, bool wait, int *exitstat,
		      int *cmdstat, char *cmdmsg,
		      gfc_charlen_type command_len,
		      gfc_charlen_type cmdmsg_len)
{
  /* Transform the Fortran string to a C string.  */
  char cmd[command_len + 1];
  memcpy (cmd, command, command_len);
  cmd[command_len] = '\0';

  /* Flush all I/O units before executing the command.  */
  flush_all_units();

#if defined(HAVE_FORK)
  if (!wait)
    {
      /* Asynchronous execution.  */
      pid_t pid;

      set_cmdstat (cmdstat, EXEC_NOERROR);

      if ((pid = fork()) < 0)
	set_cmdstat (cmdstat, EXEC_CHILDFAILED);
      else if (pid == 0)
	{
	  /* Child process.  */
	  int res = system (cmd);
	  _exit (WIFEXITED(res) ? WEXITSTATUS(res) : res);
	}
    }
  else
#endif
    {
      /* Synchronous execution.  */
      int res = system (cmd);

      if (res == -1)
	set_cmdstat (cmdstat, EXEC_SYSTEMFAILED);
      else if (!wait)
	set_cmdstat (cmdstat, EXEC_SYNCHRONOUS);
      else
	set_cmdstat (cmdstat, EXEC_NOERROR);

      if (res != -1)
	{
#if defined(WEXITSTATUS) && defined(WIFEXITED)
	  *exitstat = WIFEXITED(res) ? WEXITSTATUS(res) : res;
#else
	  *exitstat = res;
#endif
	}
    }

  /* Now copy back to the Fortran string if needed.  */
  if (cmdstat && *cmdstat > EXEC_NOERROR)
    {
      if (cmdmsg)
	fstrcpy (cmdmsg, cmdmsg_len, cmdmsg_values[*cmdstat],
		strlen (cmdmsg_values[*cmdstat]));
      else
	runtime_error ("Failure in EXECUTE_COMMAND_LINE: %s",
		       cmdmsg_values[*cmdstat]);
    }
}