当前位置: 首页>>代码示例>>C++>>正文


C++ pipe函数代码示例

本文整理汇总了C++中pipe函数的典型用法代码示例。如果您正苦于以下问题:C++ pipe函数的具体用法?C++ pipe怎么用?C++ pipe使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了pipe函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: runcmd

// Execute cmd.  Never returns.
void
runcmd(struct cmd *cmd)
{
  int p[2];
  struct backcmd *bcmd;
  struct execcmd *ecmd;
  struct listcmd *lcmd;
  struct pipecmd *pcmd;
  struct redircmd *rcmd;

  if(cmd == 0)
    exit();

  switch(cmd->type){
  default:
    panic("runcmd");

  case EXEC:
    ecmd = (struct execcmd*)cmd;
    if(ecmd->argv[0] == 0)
      exit();
    exec(ecmd->argv[0], ecmd->argv);
    printf(2, "exec %s failed\n", ecmd->argv[0]);
    break;

  case REDIR:
    rcmd = (struct redircmd*)cmd;
    close(rcmd->fd);
    if(open(rcmd->file, rcmd->mode) < 0){
      printf(2, "open %s failed\n", rcmd->file);
      exit();
    }
    runcmd(rcmd->cmd);
    break;

  case LIST:
    lcmd = (struct listcmd*)cmd;
    if(fork1() == 0)
      runcmd(lcmd->left);
    wait();
    runcmd(lcmd->right);
    break;

  case PIPE:
    pcmd = (struct pipecmd*)cmd;
    if(pipe(p) < 0)
      panic("pipe");
    if(fork1() == 0){
      close(1);
      dup(p[1]);
      close(p[0]);
      close(p[1]);
      runcmd(pcmd->left);
    }
    if(fork1() == 0){
      close(0);
      dup(p[0]);
      close(p[0]);
      close(p[1]);
      runcmd(pcmd->right);
    }
    close(p[0]);
    close(p[1]);
    wait();
    wait();
    break;

  case BACK:
    bcmd = (struct backcmd*)cmd;
    if(fork1() == 0)
      runcmd(bcmd->cmd);
    break;
  }
  exit();
}
开发者ID:i,项目名称:xv6,代码行数:76,代码来源:sh.c

示例2: start_command

int start_command(struct child_process *cmd)
{
	int need_in, need_out, need_err;
	int fdin[2], fdout[2], fderr[2];
	int failed_errno;
	char *str;

	if (!cmd->argv)
		cmd->argv = cmd->args.argv;
	if (!cmd->env)
		cmd->env = cmd->env_array.argv;

	/*
	 * In case of errors we must keep the promise to close FDs
	 * that have been passed in via ->in and ->out.
	 */

	need_in = !cmd->no_stdin && cmd->in < 0;
	if (need_in) {
		if (pipe(fdin) < 0) {
			failed_errno = errno;
			if (cmd->out > 0)
				close(cmd->out);
			str = "standard input";
			goto fail_pipe;
		}
		cmd->in = fdin[1];
	}

	need_out = !cmd->no_stdout
		&& !cmd->stdout_to_stderr
		&& cmd->out < 0;
	if (need_out) {
		if (pipe(fdout) < 0) {
			failed_errno = errno;
			if (need_in)
				close_pair(fdin);
			else if (cmd->in)
				close(cmd->in);
			str = "standard output";
			goto fail_pipe;
		}
		cmd->out = fdout[0];
	}

	need_err = !cmd->no_stderr && cmd->err < 0;
	if (need_err) {
		if (pipe(fderr) < 0) {
			failed_errno = errno;
			if (need_in)
				close_pair(fdin);
			else if (cmd->in)
				close(cmd->in);
			if (need_out)
				close_pair(fdout);
			else if (cmd->out)
				close(cmd->out);
			str = "standard error";
fail_pipe:
			error("cannot create %s pipe for %s: %s",
				str, cmd->argv[0], strerror(failed_errno));
			argv_array_clear(&cmd->args);
			argv_array_clear(&cmd->env_array);
			errno = failed_errno;
			return -1;
		}
		cmd->err = fderr[0];
	}

	trace_argv_printf(cmd->argv, "trace: run_command:");
	fflush(NULL);

#ifndef GIT_WINDOWS_NATIVE
{
	int notify_pipe[2];
	if (pipe(notify_pipe))
		notify_pipe[0] = notify_pipe[1] = -1;

	cmd->pid = fork();
	failed_errno = errno;
	if (!cmd->pid) {
		/*
		 * Redirect the channel to write syscall error messages to
		 * before redirecting the process's stderr so that all die()
		 * in subsequent call paths use the parent's stderr.
		 */
		if (cmd->no_stderr || need_err) {
			int child_err = dup(2);
			set_cloexec(child_err);
			set_error_handle(fdopen(child_err, "w"));
		}

		close(notify_pipe[0]);
		set_cloexec(notify_pipe[1]);
		child_notifier = notify_pipe[1];
		atexit(notify_parent);

		if (cmd->no_stdin)
			dup_devnull(0);
		else if (need_in) {
//.........这里部分代码省略.........
开发者ID:allenbh,项目名称:git,代码行数:101,代码来源:run-command.c

示例3: CloudPinyinCreate

void* CloudPinyinCreate(FcitxInstance* instance)
{
    FcitxCloudPinyin *cloudpinyin = fcitx_utils_new(FcitxCloudPinyin);
    bindtextdomain("fcitx-cloudpinyin", LOCALEDIR);
    bind_textdomain_codeset("fcitx-cloudpinyin", "UTF-8");
    cloudpinyin->owner = instance;
    int pipe1[2];
    int pipe2[2];

    if (!CloudPinyinConfigLoad(&cloudpinyin->config))
    {
        free(cloudpinyin);
        return NULL;
    }

    if (pipe(pipe1) < 0)
    {
        free(cloudpinyin);
        return NULL;
    }

    if (pipe(pipe2) < 0) {
        close(pipe1[0]);
        close(pipe1[1]);
        free(cloudpinyin);
        return NULL;
    }

    cloudpinyin->pipeRecv = pipe1[0];
    cloudpinyin->pipeNotify = pipe2[1];

    fcntl(pipe1[0], F_SETFL, O_NONBLOCK);
    fcntl(pipe1[1], F_SETFL, O_NONBLOCK);
    fcntl(pipe2[0], F_SETFL, O_NONBLOCK);
    fcntl(pipe2[1], F_SETFL, O_NONBLOCK);

    cloudpinyin->pendingQueue = fcitx_utils_malloc0(sizeof(CurlQueue));
    cloudpinyin->finishQueue = fcitx_utils_malloc0(sizeof(CurlQueue));
    pthread_mutex_init(&cloudpinyin->pendingQueueLock, NULL);
    pthread_mutex_init(&cloudpinyin->finishQueueLock, NULL);

    FcitxFetchThread* fetch = fcitx_utils_malloc0(sizeof(FcitxFetchThread));
    cloudpinyin->fetch = fetch;
    fetch->owner = cloudpinyin;
    fetch->pipeRecv = pipe2[0];
    fetch->pipeNotify = pipe1[1];
    fetch->pendingQueueLock = &cloudpinyin->pendingQueueLock;
    fetch->finishQueueLock = &cloudpinyin->finishQueueLock;
    fetch->queue = fcitx_utils_malloc0(sizeof(CurlQueue));

    FcitxIMEventHook hook;
    hook.arg = cloudpinyin;
    hook.func = CloudPinyinAddCandidateWord;

    FcitxInstanceRegisterUpdateCandidateWordHook(instance, hook);

    hook.arg = cloudpinyin;
    hook.func = CloudPinyinHookForNewRequest;

    FcitxInstanceRegisterResetInputHook(instance, hook);
    FcitxInstanceRegisterInputFocusHook(instance, hook);
    FcitxInstanceRegisterInputUnFocusHook(instance, hook);
    FcitxInstanceRegisterTriggerOnHook(instance, hook);

    FcitxHotkeyHook hkhook;
    hkhook.arg = cloudpinyin;
    hkhook.hotkey = cloudpinyin->config.hkToggle.hotkey;
    hkhook.hotkeyhandle = CloudPinyinToggle;

    FcitxInstanceRegisterHotkeyFilter(instance, hkhook);

    pthread_create(&cloudpinyin->pid, NULL, FetchThread, fetch);

    CloudPinyinRequestKey(cloudpinyin);

    return cloudpinyin;
}
开发者ID:cherry-wb,项目名称:fcitx-cloudpinyin,代码行数:77,代码来源:cloudpinyin.c

示例4: roken_detach_prep

ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
roken_detach_prep(int argc, char **argv, char *special_arg)
{
    pid_t child;
    char buf[1];
    ssize_t bytes;
    int status;

    pipefds[0] = -1;
    pipefds[1] = -1;

#ifdef WIN32
    if (_pipe(pipefds, 4, O_BINARY) == -1)
        err(1, "failed to setup to detach daemon (_pipe failed)");
#else
    if (pipe(pipefds) == -1)
        err(1, "failed to setup to detach daemon (pipe failed)");
#endif

#ifndef WIN32
    fflush(stdout);
    child = fork();
#else
    {
        intptr_t child_handle;
	int write_side;
        size_t i;
	char *fildes;
        char **new_argv;

        new_argv = calloc(argc + 2, sizeof(*new_argv));
        if (new_argv == NULL)
            err(1, "Out of memory");

	write_side = _dup(pipefds[1]); /* The new fd will be inherited */
	if (write_side == -1)
            err(1, "Out of memory");

	if (asprintf(&fildes, "%d", write_side) == -1 ||
	    fildes == NULL)
            err(1, "failed to setup to detach daemon (_dup failed)");

        new_argv[0] = argv[0];
        new_argv[1] = special_arg;
        new_argv[2] = fildes;
        for (i = 1; argv[i] != NULL; i++)
            new_argv[i + 1] = argv[i];
	new_argv[argc + 2] = NULL;

	_flushall();
	child_handle = spawnvp(_P_NOWAIT, argv[0], new_argv);
	if (child_handle == -1)
	  child = (pid_t)-1;
	else
	  child = GetProcessId((HANDLE)child_handle);
    }
#endif
    if (child == (pid_t)-1)
        err(1, "failed to setup to fork daemon (fork failed)");

#ifndef WIN32
    if (child == 0) {
        int fd;

        (void) close(pipefds[0]);
        pipefds[0] = -1;
        /*
         * Keep stdout/stderr for now so output and errors prior to
         * detach_finish() can be seen by the user.
         */
        fd = open(_PATH_DEVNULL, O_RDWR, 0);
        if (fd == -1)
            err(1, "failed to open /dev/null");
        (void) dup2(fd, STDIN_FILENO);
        if (fd > STDERR_FILENO)
            (void) close(fd);
        return;
    }
#endif

    (void) close(pipefds[1]);
    pipefds[1] = -1;
    do {
        bytes = read(pipefds[0], buf, sizeof(buf));
    } while (bytes == -1 && errno == EINTR);
    (void) close(pipefds[0]);
    pipefds[0] = -1;
    if (bytes == -1) {
        /*
         * No need to wait for the process.  We've killed it.  If it
         * doesn't want to exit, we'd have to wait potentially forever,
         * but we want to indicate failure to the user as soon as
         * possible.  A wait with timeout would end the same way
         * (attempting to kill the process).
         */
        err(1, "failed to setup daemon child (read from child pipe)");
    }
    if (bytes == 0) {
        warnx("daemon child preparation failed, waiting for child");
        status = wait_for_process(child);
//.........这里部分代码省略.........
开发者ID:DavidMulder,项目名称:heimdal,代码行数:101,代码来源:detach.c

示例5: forkpty

pid_t
forkpty(int *master, unused char *name, struct termios *tio, struct winsize *ws)
{
	int	slave = -1, fd, pipe_fd[2];
	char   *path, dummy;
	pid_t	pid;

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

	if ((*master = open("/dev/ptc", O_RDWR|O_NOCTTY)) == -1)
		goto out;

	if ((path = ttyname(*master)) == NULL)
		goto out;
	if ((slave = open(path, O_RDWR|O_NOCTTY)) == -1)
		goto out;

	switch (pid = fork()) {
	case -1:
		goto out;
	case 0:
		close(*master);

		close(pipe_fd[1]);
		while (read(pipe_fd[0], &dummy, 1) == -1) {
			if (errno != EINTR)
				break;
		}
		close(pipe_fd[0]);

		fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
		if (fd >= 0) {
			ioctl(fd, TIOCNOTTY, NULL);
			close(fd);
		}

		if (setsid() < 0)
			fatal("setsid");

		fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
		if (fd >= 0)
			fatalx("open succeeded (failed to disconnect)");

		fd = open(path, O_RDWR);
		if (fd < 0)
			fatal("open failed");
		close(fd);

		fd = open("/dev/tty", O_WRONLY);
		if (fd < 0)
			fatal("open failed");
		close(fd);

		if (tio != NULL && tcsetattr(slave, TCSAFLUSH, tio) == -1)
			fatal("tcsetattr failed");
		if (ioctl(slave, TIOCSWINSZ, ws) == -1)
			fatal("ioctl failed");

		dup2(slave, 0);
		dup2(slave, 1);
		dup2(slave, 2);
		if (slave > 2)
			close(slave);

		return (0);
	}

	close(slave);

	close(pipe_fd[0]);
	close(pipe_fd[1]);
	return (pid);

out:
	if (*master != -1)
		close(*master);
	if (slave != -1)
		close(slave);

	close(pipe_fd[0]);
	close(pipe_fd[1]);
	return (-1);
}
开发者ID:Darkoe,项目名称:tmux,代码行数:84,代码来源:forkpty-aix.c

示例6: memset

/*
 * Run an external program. Optionally wait a specified number
 *   of seconds. Program killed if wait exceeded. We open
 *   a bi-directional pipe so that the user can read from and
 *   write to the program.
 */
BPIPE *open_bpipe(char *prog, int wait, const char *mode)
{
   char *bargv[MAX_ARGV];
   int bargc, i;
   int readp[2], writep[2];
   POOLMEM *tprog;
   int mode_read, mode_write;
   BPIPE *bpipe;
   int save_errno;

   bpipe = (BPIPE *)malloc(sizeof(BPIPE));
   memset(bpipe, 0, sizeof(BPIPE));
   mode_read = (mode[0] == 'r');
   mode_write = (mode[0] == 'w' || mode[1] == 'w');
   /* Build arguments for running program. */
   tprog = get_pool_memory(PM_FNAME);
   pm_strcpy(tprog, prog);
   build_argc_argv(tprog, &bargc, bargv, MAX_ARGV);
#ifdef  xxxxxx
   printf("argc=%d\n", bargc);
   for (i=0; i<bargc; i++) {
      printf("argc=%d argv=%s:\n", i, bargv[i]);
   }
#endif

   /* Each pipe is one way, write one end, read the other, so we need two */
   if (mode_write && pipe(writep) == -1) {
      save_errno = errno;
      free(bpipe);
      free_pool_memory(tprog);
      errno = save_errno;
      return NULL;
   }
   if (mode_read && pipe(readp) == -1) {
      save_errno = errno;
      if (mode_write) {
         close(writep[0]);
         close(writep[1]);
      }
      free(bpipe);
      free_pool_memory(tprog);
      errno = save_errno;
      return NULL;
   }
   /* Start worker process */
   switch (bpipe->worker_pid = fork()) {
   case -1:                           /* error */
      save_errno = errno;
      if (mode_write) {
         close(writep[0]);
         close(writep[1]);
      }
      if (mode_read) {
         close(readp[0]);
         close(readp[1]);
      }
      free(bpipe);
      free_pool_memory(tprog);
      errno = save_errno;
      return NULL;

   case 0:                            /* child */
      if (mode_write) {
         close(writep[1]);
         dup2(writep[0], 0);          /* Dup our write to his stdin */
      }
      if (mode_read) {
         close(readp[0]);             /* Close unused child fds */
         dup2(readp[1], 1);           /* dup our read to his stdout */
         dup2(readp[1], 2);           /*   and his stderr */
      }
/* Note, the close log cause problems, see bug #1536 */
/*    closelog();                        close syslog if open */
      for (i=3; i<=32; i++) {         /* close any open file descriptors */
         close(i);
      }
      execvp(bargv[0], bargv);        /* call the program */
      /* Convert errno into an exit code for later analysis */
      for (i=0; i< num_execvp_errors; i++) {
         if (execvp_errors[i] == errno) {
            exit(200 + i);            /* exit code => errno */
         }
      }
      exit(255);                      /* unknown errno */

   default:                           /* parent */
      break;
   }
   free_pool_memory(tprog);
   if (mode_read) {
      close(readp[1]);                /* close unused parent fds */
      bpipe->rfd = fdopen(readp[0], "r"); /* open file descriptor */
   }
   if (mode_write) {
//.........这里部分代码省略.........
开发者ID:eneuhauss,项目名称:bareos,代码行数:101,代码来源:bpipe.c

示例7: cmd_clipboard

void
cmd_clipboard(const char *e_line, command *commands)
{
	xmlNodePtr		db_node = NULL;
	xmlChar			*key = NULL, *value = NULL, *value_nl = NULL, *value_line = NULL;
	char			*cmd_line = NULL, *cmd = NULL, *inv = NULL;
	unsigned long int	idx = 0, line_req = 1, lines = 0, value_line_len = 0, value_len = 0, i = 0;
	unsigned char		app = 0;	/* 1=tmux, 2=xclip PRIMARY, 3=xclip CLIPBOARD */

	char		**fork_argv = NULL;
	int		child;
	int		pipefd[2];


	cmd_line = strdup(e_line); malloc_check(cmd_line);

	cmd = strtok(cmd_line, " ");
	if (!cmd) {
		puts(commands->usage);

		free(cmd_line); cmd_line = NULL;
		return;
	}

	if (strcmp(cmd, "tmux") == 0)
		app = 1;
	else if (strcmp(cmd, "xclip") == 0)
		app = 2;
	else if (strcmp(cmd, "Xclip") == 0)
		app = 3;

	if (app == 0) {
		puts(commands->usage);

		free(cmd_line); cmd_line = NULL;
		return;
	}


	cmd = strtok(NULL, " ");	/* first parameter, the index number */
	if (!cmd) {
		puts(commands->usage);

		free(cmd_line); cmd_line = NULL;
		return;
	}

	errno = 0;
	idx = strtoul((const char *)cmd, &inv, 10);
	if (inv[0] != '\0'  ||  errno != 0  ||  cmd[0] == '-') {
		puts(commands->usage);

		free(cmd_line); cmd_line = NULL;
		return;
	}


	cmd = strtok(NULL, " ");	/* second, optional parameter, the requested line number */
	if (cmd) {
		errno = 0;
		line_req = strtoul((const char *)cmd, &inv, 10);
		if (inv[0] != '\0'  ||  errno != 0  ||  cmd[0] == '-') {
			puts(commands->usage);

			free(cmd_line); cmd_line = NULL;
			return;
		}
		if (line_req < 1) {
			puts(commands->usage);

			free(cmd_line); cmd_line = NULL;
			return;
		}
	}

	free(cmd_line); cmd_line = NULL;


	db_node = find_key(idx);
	if (db_node) {
		value = xmlGetProp(db_node, BAD_CAST "value");
		key = xmlGetProp(db_node, BAD_CAST "name");
		value_nl = parse_newlines(value, 0);
		xmlFree(value); value = NULL;

		/* count how many (new)lines are in the string */
		value_len = xmlStrlen(value_nl);
		for (i=0; i < value_len; i++)
			if (value_nl[i] == '\n')
				lines++;
		lines++;

		/* If the requested line number is greater than the
		 * maximum, use the maximum.
		 */
		if (line_req > lines)
			line_req = lines;

		/* get a line out from the value */
		value_line = get_line(value_nl, line_req);
//.........这里部分代码省略.........
开发者ID:levaidaniel,项目名称:kc,代码行数:101,代码来源:cmd_clipboard.c

示例8: textToVariable

/*
 *  The purpose of this function is to assign "long usage", short usage
 *  and version information to a shell variable.  Rather than wind our
 *  way through all the logic necessary to emit the text directly, we
 *  fork(), have our child process emit the text the normal way and
 *  capture the output in the parent process.
 */
static void
textToVariable(tOptions * pOpts, teTextTo whichVar, tOptDesc * pOD)
{
#   define _TT_(n) static char const z ## n [] = #n;
    TEXTTO_TABLE
#   undef _TT_
#   define _TT_(n) z ## n ,
      static char const * apzTTNames[] = { TEXTTO_TABLE };
#   undef _TT_

#if ! defined(HAVE_WORKING_FORK)
    printf("%1$s_%2$s_TEXT='no %2$s text'\n",
           pOpts->pzPROGNAME, apzTTNames[ whichVar ]);
#else
    int  pipeFd[2];

    fflush(stdout);
    fflush(stderr);

    if (pipe(pipeFd) != 0) {
        fprintf(stderr, zBadPipe, errno, strerror(errno));
        exit(EXIT_FAILURE);
    }

    switch (fork()) {
    case -1:
        fprintf(stderr, zForkFail, errno, strerror(errno), pOpts->pzProgName);
        exit(EXIT_FAILURE);
        break;

    case 0:
        /*
         * Send both stderr and stdout to the pipe.  No matter which
         * descriptor is used, we capture the output on the read end.
         */
        dup2(pipeFd[1], STDERR_FILENO);
        dup2(pipeFd[1], STDOUT_FILENO);
        close(pipeFd[0]);

        switch (whichVar) {
        case TT_LONGUSAGE:
            (*(pOpts->pUsageProc))(pOpts, EXIT_SUCCESS);
            /* NOTREACHED */

        case TT_USAGE:
            (*(pOpts->pUsageProc))(pOpts, EXIT_FAILURE);
            /* NOTREACHED */

        case TT_VERSION:
            if (pOD->fOptState & OPTST_ALLOC_ARG) {
                AGFREE(pOD->optArg.argString);
                pOD->fOptState &= ~OPTST_ALLOC_ARG;
            }
            pOD->optArg.argString = "c";
            optionPrintVersion(pOpts, pOD);
            /* NOTREACHED */

        default:
            exit(EXIT_FAILURE);
        }

    default:
        close(pipeFd[1]);
    }

    emit_var_text(pOpts->pzPROGNAME, apzTTNames[whichVar], pipeFd[0]);
#endif
}
开发者ID:Distrotech,项目名称:ntp,代码行数:75,代码来源:makeshell.c

示例9: OS_Create_Process

//
//  OS_Create_Process: C
// 
// flags:
//     1: wait, is implied when I/O redirection is enabled
//     2: console
//     4: shell
//     8: info
//     16: show
// 
// input_type/output_type/err_type:
//     0: none
//     1: string
//     2: file
// 
// Return -1 on error, otherwise the process return code.
// 
// POSIX previous simple version was just 'return system(call);'
// This uses 'execvp' which is "POSIX.1 conforming, UNIX compatible"
//
int OS_Create_Process(
    const REBCHR *call,
    int argc,
    const REBCHR* argv[],
    u32 flags,
    u64 *pid,
    int *exit_code,
    u32 input_type,
    char *input,
    u32 input_len,
    u32 output_type,
    char **output,
    u32 *output_len,
    u32 err_type,
    char **err,
    u32 *err_len
) {
    REBOOL flag_wait = FALSE;
    REBOOL flag_console = FALSE;
    REBOOL flag_shell = FALSE;
    REBOOL flag_info = FALSE;
    int stdin_pipe[] = {-1, -1};
    int stdout_pipe[] = {-1, -1};
    int stderr_pipe[] = {-1, -1};
    int info_pipe[] = {-1, -1};
    int status = 0;
    int ret = 0;
    char *info = NULL;
    off_t info_size = 0;
    u32 info_len = 0;
    pid_t fpid = 0;

    const unsigned int R = 0;
    const unsigned int W = 1;

    // We want to be able to compile with all warnings as errors, and
    // we'd like to use -Wcast-qual if possible.  This is currently
    // the only barrier in the codebase...so we tunnel under the cast.
    char * const *argv_hack;

    if (flags & FLAG_WAIT) flag_wait = TRUE;
    if (flags & FLAG_CONSOLE) flag_console = TRUE;
    if (flags & FLAG_SHELL) flag_shell = TRUE;
    if (flags & FLAG_INFO) flag_info = TRUE;

    // suppress unused warnings but keep flags for future use
    (void)flag_info;
    (void)flag_console;

    // NOTE: pipe() is POSIX, but pipe2() is Linux-specific.

    if (input_type == STRING_TYPE
        || input_type == BINARY_TYPE) {
    #ifdef TO_LINUX
        if (pipe2(stdin_pipe, O_CLOEXEC | O_NONBLOCK) < 0) {
    #else
        if (pipe(stdin_pipe) < 0) {
    #endif
            goto stdin_pipe_err;
        }
    }
    if (output_type == STRING_TYPE || output_type == BINARY_TYPE) {
    #ifdef TO_LINUX
        if (pipe2(stdout_pipe, O_CLOEXEC | O_NONBLOCK) < 0) {
    #else
        if (pipe(stdout_pipe) < 0) {
    #endif
            goto stdout_pipe_err;
        }
    }
    if (err_type == STRING_TYPE || err_type == BINARY_TYPE) {
    #ifdef TO_LINUX
        if (pipe2(stderr_pipe, O_CLOEXEC | O_NONBLOCK) < 0) {
    #else
        if (pipe(stderr_pipe) < 0) {
    #endif
            goto stderr_pipe_err;
        }
    }

//.........这里部分代码省略.........
开发者ID:kjanz1899,项目名称:ren-c,代码行数:101,代码来源:host-process.c

示例10: ngx_rtmp_exec_run

static ngx_int_t
ngx_rtmp_exec_run(ngx_rtmp_exec_t *e)
{
#if !(NGX_WIN32)
    ngx_pid_t                       pid;
    int                             fd, maxfd;
    int                             pipefd[2];
    int                             ret;
    ngx_rtmp_exec_conf_t           *ec;
    ngx_str_t                      *arg, a;
    char                          **args;
    ngx_uint_t                      n;

    ec = e->conf;

    ngx_log_debug1(NGX_LOG_DEBUG_RTMP, e->log, 0,
                   "exec: starting child '%V'", &ec->cmd);

    if (e->active) {
        ngx_log_debug1(NGX_LOG_DEBUG_RTMP, e->log, 0,
                       "exec: already active '%V'", &ec->cmd);
        return NGX_OK;
    }

    if (pipe(pipefd) == -1) {
        ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
                      "exec: pipe failed");
        return NGX_ERROR;
    }

    /* make pipe write end survive through exec */
    ret = fcntl(pipefd[1], F_GETFD);
    if (ret != -1) {
        ret &= ~FD_CLOEXEC;
        ret = fcntl(pipefd[1], F_SETFD, ret);
    }
    if (ret == -1) {
        close(pipefd[0]);
        close(pipefd[1]);
        ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
                      "exec: fcntl failed");
        return NGX_ERROR;
    }

    pid = fork();
    switch (pid) {
        case -1:
            close(pipefd[0]);
            close(pipefd[1]);
            ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
                          "exec: fork failed");
            return NGX_ERROR;

        case 0:
            /* child */

#if (NGX_LINUX)
            prctl(PR_SET_PDEATHSIG, e->kill_signal, 0, 0, 0);
#endif

            /* close all descriptors but pipe write end */
            maxfd = sysconf(_SC_OPEN_MAX);
            for (fd = 0; fd < maxfd; ++fd) {
                if (fd == pipefd[1]) {
                    continue;
                }

                close(fd);
            }

            fd = open("/dev/null", O_RDWR);            

            dup2(fd, STDIN_FILENO);
            dup2(fd, STDOUT_FILENO);
            dup2(fd, STDERR_FILENO);

            args = ngx_alloc((ec->args.nelts + 2) * sizeof(char *), e->log);
            if (args == NULL) {
                exit(1);
            }
            arg = ec->args.elts;
            args[0] = (char *) ec->cmd.data;
            for (n = 0; n < ec->args.nelts; ++n, ++arg) {
                if (e->session == NULL) {
                    a = *arg;
                } else {
                    ngx_rtmp_eval(e->session, arg, ngx_rtmp_exec_eval_p, &a);
                }
                args[n + 1] = (char *) a.data;
            }
            args[n + 1] = NULL;
            if (execvp((char *) ec->cmd.data, args) == -1) {
                exit(1);
            }
            break;

        default:
            /* parent */
            close(pipefd[1]);
            e->active = 1;
//.........这里部分代码省略.........
开发者ID:alcemirfernandes,项目名称:nginx-rtmp-module,代码行数:101,代码来源:ngx_rtmp_exec_module.c

示例11: main

int main(int argc, char **argv)
{
    /* UCP temporary vars */
    ucp_params_t ucp_params;
    ucp_worker_params_t worker_params;
    ucp_config_t *config;
    ucs_status_t status;

    /* UCP handler objects */
    ucp_context_h ucp_context;

    /* OOB connection vars */
    uint64_t addr_len = 0;
    char *server = NULL;
    int oob_sock = -1;
    int ret = -1;

    /* create the signalling pipe */
    pipe(signal_pipe);


    /* Parse the command line */
    if (parse_cmd(argc, argv, &server) != UCS_OK) {
        goto err;
    }
    /* UCP initialization */
    status = ucp_config_read(NULL, NULL, &config);
    if (status != UCS_OK) {
        goto err;
    }

    ucp_params.features = UCP_FEATURE_TAG;
    if (ucp_test_mode == TEST_MODE_WAIT || ucp_test_mode == TEST_MODE_EVENTFD) {
        ucp_params.features |= UCP_FEATURE_WAKEUP;
    }
    ucp_params.request_size    = sizeof(struct ucx_context);
    ucp_params.request_init    = request_init;
    ucp_params.request_cleanup = NULL;

    status = ucp_init(&ucp_params, config, &ucp_context);

    ucp_config_print(config, stdout, NULL, UCS_CONFIG_PRINT_CONFIG);

    ucp_config_release(config);
    if (status != UCS_OK) {
        goto err;
    }

    worker_params.field_mask  = UCP_WORKER_PARAM_FIELD_THREAD_MODE;
    worker_params.thread_mode = UCS_THREAD_MODE_SINGLE;

    status = ucp_worker_create(ucp_context, &worker_params, &ucp_worker);
    if (status != UCS_OK) {
        goto err_cleanup;
    }

    status = ucp_worker_get_address(ucp_worker, &local_addr, &local_addr_len);
    if (status != UCS_OK) {
        goto err_worker;
    }

    status = ucp_worker_get_efd(ucp_worker, &epoll_fd);
    if (status != UCS_OK) {
        goto err;
    }

    printf("[0x%x] local address length: %zu\n",
           (unsigned int)pthread_self(), local_addr_len);

    /* OOB connection establishment */
    if (server) {
        peer_addr_len = local_addr_len;

        oob_sock = run_client(server);
        if (oob_sock < 0) {
            goto err_addr;
        }

        ret = recv(oob_sock, &addr_len, sizeof(addr_len), 0);
        if (ret < 0) {
            fprintf(stderr, "failed to receive address length\n");
            goto err_addr;
        }

        peer_addr_len = addr_len;
        peer_addr = malloc(peer_addr_len);
        if (!peer_addr) {
            fprintf(stderr, "unable to allocate memory\n");
            goto err_addr;
        }

        ret = recv(oob_sock, peer_addr, peer_addr_len, 0);
        if (ret < 0) {
            fprintf(stderr, "failed to receive address\n");
            goto err_peer_addr;
        }
    } else {
        oob_sock = run_server();
        if (oob_sock < 0) {
            goto err_peer_addr;
//.........这里部分代码省略.........
开发者ID:artpol84,项目名称:poc,代码行数:101,代码来源:ucp_latency.c

示例12: mypipe

int
mypipe(int *fd)
{
	return pipe(fd);
}
开发者ID:8l,项目名称:NxM,代码行数:5,代码来源:Posix.c

示例13: exec_conf

static int exec_conf(void)
{
	int pipefd[2], stat, size;
	struct sigaction sa;
	sigset_t sset, osset;

	sigemptyset(&sset);
	sigaddset(&sset, SIGINT);
	sigprocmask(SIG_BLOCK, &sset, &osset);

	signal(SIGINT, SIG_DFL);

	sa.sa_handler = winch_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	sigaction(SIGWINCH, &sa, NULL);

	*argptr++ = NULL;

	pipe(pipefd);
	pid = fork();
	if (pid == 0) {
		sigprocmask(SIG_SETMASK, &osset, NULL);
		dup2(pipefd[1], 2);
		close(pipefd[0]);
		close(pipefd[1]);
		execv(args[0], args);
		_exit(EXIT_FAILURE);
	}

	close(pipefd[1]);
	bufptr = input_buf;
	while (1) {
		size = input_buf + sizeof(input_buf) - bufptr;
		size = read(pipefd[0], bufptr, size);
		if (size <= 0) {
			if (size < 0) {
				if (errno == EINTR || errno == EAGAIN)
					continue;
				perror("read");
			}
			break;
		}
		bufptr += size;
	}
	*bufptr++ = 0;
	close(pipefd[0]);
	waitpid(pid, &stat, 0);

	if (do_resize) {
		init_wsize();
		do_resize = 0;
		sigprocmask(SIG_SETMASK, &osset, NULL);
		return -1;
	}
	if (WIFSIGNALED(stat)) {
		printf("\finterrupted(%d)\n", WTERMSIG(stat));
		exit(1);
	}
#if 0
	printf("\fexit state: %d\nexit data: '%s'\n", WEXITSTATUS(stat), input_buf);
	sleep(1);
#endif
	sigpending(&sset);
	if (sigismember(&sset, SIGINT)) {
		printf("\finterrupted\n");
		exit(1);
	}
	sigprocmask(SIG_SETMASK, &osset, NULL);

	return WEXITSTATUS(stat);
}
开发者ID:jameshilliard,项目名称:20-4-4,代码行数:72,代码来源:mconf.c

示例14: main

int
main(int argc, char *argv[])
{
    int                     n;
    int                     fd[2];
    pid_t                   pid;
    char                    *pager, *argv0;
    char                    line[1024];
    FILE                    *fp;

    if(argc != 2){
        printf("usage: a.out <pathname>\n");
        return -1;
    }

    if((fp = fopen(argv[1], "r")) == NULL){
        printf("open file [%s] error: %s\n", argv[1], strerror(errno));
        return -2;
    }
    
    if(pipe(fd) < 0){
        perror("pipe");
        return -3;
    }

    if((pid = fork()) < 0){
        perror("fork");
        return -4;
    }else if(pid > 0){
        close(fd[0]);
        while(fgets(line, sizeof(line), fp) != NULL){
            n = strlen(line);
            if(write(fd[1], line, n) != n){
                perror("write");
                return -5;
            }
        }
        if(ferror(fp)){ /*读文件结束或者读文件出错,fgets都会返回NULL,用ferror来判断是不是发生了错误*/
            printf("read file [%s] error\n", argv[1]);
            return -6;
        }

        close(fd[1]);

        /*等待子进程退出*/
        if(waitpid(pid, NULL, 0) < 0){
            perror("waitpid");
            return -7;
        }

        return 0;
    }else{
        close(fd[1]);
        /*要先判断是不相等了才进行文件符复制*/
        if(fd[0] != STDIN_FILENO){
            if(dup2(fd[0], STDIN_FILENO) != STDIN_FILENO){
                perror("dup2");
                return -8;
            }
            close(fd[0]);/*要关闭该文件描述符,因为被复制出来了,共享文件描述符,以后都不用了*/
        }
        /*文件描述符已被复制,子进程的标准输入是管道了,即复制前的fd[0]*/
        /*获取页的大小*/
        if((pager = getenv("PAGER")) == NULL)
            pager = DEF_PAGER;
        if((argv0 = strrchr(pager, '/')) != NULL)
            argv0++;
        else
            argv0 = pager;

        if(execl(pager, argv0, (char *)0) < 0){
            perror("execl");
            return -9;
        }
        return 0;
    }
    
}
开发者ID:lufb,项目名称:code,代码行数:78,代码来源:pipe_advance.c

示例15: proc_create

int		proc_create(proc_obj_t* proc, char* bin_path, char** args)
{
  pid_t		child;
  int		pfd1[2], pfd2[2];
  char		c;
  ttevent_t	ev;

  ev.tte_events = TTEVT_SYSCALL|TTEVT_EXEC|TTEVT_EXIT|
    TTEVT_BPT_SSTEP|TTEVT_SIGNAL;
  ev.tte_opts = TTEO_NONE;

  /*
  ** Technique de Roumain avec des pipes
  ** pour synchoniser les deux process
  */
  if (pipe(pfd1) < 0 || pipe(pfd2) < 0)
    return (-1);
  switch ((child = fork()))
    {
    case -1:
      return (-1);

      /*
      ** Child Process
      */
    case 0:
      if (setpgid(0, 0) == -1)
	return (-1);
      if (ttrace(TT_PROC_SETTRC, 0, 0, 0, TT_VERSION, 0) == -1)
	return -1;
      /* tell parent we are SETTRC'ed */
      if (write(pfd2[1], (void *)&c, sizeof c) != sizeof c)
	return (-1);
      /* wait for exec event to be set*/
      if (read(pfd1[0], (void *)&c, sizeof c) != sizeof c)
	return (-1);
      close(pfd1[0]); close(pfd1[1]); close(pfd2[0]); close(pfd2[1]);
      if (execvp(bin_path, args) == -1)
	return (-1);
      return (-1);
    }
  /*
  ** Ftrace process
  */
  if (read(pfd2[0], (void *)&c, sizeof c) != sizeof c)
    return (-1);
  proc->pid = child;
  if (ttrace(TT_PROC_SET_EVENT_MASK, proc->pid, 0,
	     (uint64_t)&ev, sizeof ev, 0) == -1)
    return (-1);
  /* tell the child to exec */
  if (write(pfd1[1], (void *)&c, sizeof c) != sizeof c)
    return (-1);
  close(pfd1[0]); close(pfd1[1]); close(pfd2[0]); close(pfd2[1]);

  /*
  ** TODO:
  ** Attendre la fin de l'exec()
  ** set des breakpoints
  */

  proc->luse = NULL;
  if (proc_wait_debug_event(proc, NULL) == -1)
    return (-1);

  return child;
}
开发者ID:nicolascormier,项目名称:ncormier-academic-projects,代码行数:67,代码来源:low_layer.c


注:本文中的pipe函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。