• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ dup函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: spawn_proc

int spawn_proc(int in,int out,pc node,int redirectFlag,char *homedir)
{
    int no_of_tokens=0,std_out;
    pid_t pid;
    char **argv=malloc ( 100 * sizeof(char)); //Number of tokens there can be
    pid=fork();
    if(pid<0)
    {
        fprintf(stderr, "Error in Piping!\n" );
    }
    else if(pid==0) /* Child */
    {
        infile=0;
        outfile=0;
        int random=isRedirect(node.argv);
        no_of_tokens=parseCommand(node.argv,argv,redirectFlag);
        if(in!=0)
        {
            dup2(in,0);
            close(in);
        }
        if(out!=1)
        {
            dup2(out,1);
            close(out);
        }
        if(outfile!=0)
        {
            int fd1;
            if(outfile==1)
            {
                fd1=open(output,O_CREAT|O_RDWR|O_TRUNC,00666);
                lseek(fd1, 0, SEEK_SET);
            }
            else if(outfile==2)
            {
                fd1=open(output,O_APPEND|O_CREAT|O_RDWR,00666);
            }
            if(fd1==-1)
            {
                fprintf(stderr, "Can't open file for output!\n");
                memset(output, 0, 10);
                outfile=0;
                return;
            }
            int std_out=dup(1);
            dup2(fd1,STDOUT_FILENO);
            close(fd1);
            memset(output, 0, 10);
            outfile=0;
            //redirectFlag=0;
        }
        if(infile==3)
        {
            int fd2;
            fd2=open(inputfile,O_RDWR,00666);
            if(fd2==-1)
            {
                fprintf(stderr, "Can't open file for input! 2\n");
                memset(inputfile, 0, 10);
                infile=0;
                return;
            }
            dup2(fd2,STDIN_FILENO);
            close(fd2);
            memset(inputfile, 0, 10);
            infile=0;
            //redirectFlag=0;
        }
        if(isBuiltInCommand(argv[0])==1)
        {
            job_no++;
            addJob(0,argv[0],0,job_no);
            executeBuiltInCommand(argv[0],argv,no_of_tokens,homedir);
            dup2(std_out,1);
            _exit(1);
        }
        else
            return (execvp(argv[0],argv));
    }
    return pid;
}
开发者ID:SaumyaRawat,项目名称:Shell,代码行数:82,代码来源:shell.c


示例2: main

int main (int argc, char const *const *argv, char const *const *envp)
{
  char const *def = 0 ;
  int insist = 0, chomp = 0 ;
  PROG = "backtick" ;
  {
    subgetopt_t l = SUBGETOPT_ZERO ;
    for (;;)
    {
      register int opt = subgetopt_r(argc, argv, "eniD:", &l) ;
      if (opt == -1) break ;
      switch (opt)
      {
	case 'e' : break ; /* compat */
        case 'n' : chomp = 1 ; break ;
        case 'i' : insist = 1 ; break ;
        case 'D' : def = l.arg ; break ;
        default : dieusage() ;
      }
    }
    argc -= l.ind ; argv += l.ind ;
  }
  if (argc < 2) dieusage() ;
  if (!argv[0][0]) dieusage() ;
  if (!argv[1][0]) strerr_dief1x(100, "empty block") ;
  {
    unsigned int m = 0, i = 1 ;
    int fd = dup(0) ;
    char const *newargv[argc + 15] ;
    char fmt[UINT_FMT] ;
    if (fd < 0)
    {
      if (errno != EBADF) strerr_diefu1sys(111, "dup stdin") ;
    }
    else fmt[uint_fmt(fmt, (unsigned int)fd)] = 0 ;
    newargv[m++] = EXECLINE_BINPREFIX "pipeline" ;
    newargv[m++] = "--" ;
    while (argv[i] && argv[i][0] != EXECLINE_BLOCK_END_CHAR && (!EXECLINE_BLOCK_END_CHAR || (argv[i][0] && argv[i][1])))
      newargv[m++] = argv[i++] ;
    if (!argv[i]) strerr_dief1x(100, "unterminated block") ;
    newargv[m++] = "" ; i++ ;
    newargv[m++] = EXECLINE_BINPREFIX "withstdinas" ;
    if (insist) newargv[m++] = "-i" ;
    if (chomp) newargv[m++] = "-n" ;
    if (def)
    {
      newargv[m++] = "-D" ;
      newargv[m++] = def ;
    }
    newargv[m++] = "-!" ;
    newargv[m++] = "--" ;
    newargv[m++] = argv[0] ;
    if (fd < 0)
    {
      newargv[m++] = EXECLINE_BINPREFIX "fdclose" ;
      newargv[m++] = "0" ;
    }
    else
    {
      newargv[m++] = EXECLINE_BINPREFIX "fdmove" ;
      newargv[m++] = "0" ;
      newargv[m++] = fmt ;
    }
    while (argv[i]) newargv[m++] = argv[i++] ;
    newargv[m++] = 0 ;
    pathexec_run(newargv[0], newargv, envp) ;
    strerr_dieexec(111, newargv[0]) ;
  }
}
开发者ID:bitgaming,项目名称:execline,代码行数:69,代码来源:backtick.c


示例3: exec_cmd_node


//.........这里部分代码省略.........
        // create global pipe node
        pipe(tmp_global_pipe);
        output_pipe_fd = tmp_global_pipe[1];

        // broad cast message
        // *** (name) (#<client id>) just piped '(command line)' to (receiver's name) (#<receiver's client_id>) ***
        char* msg_temp = "*** %s (#%d) just piped '%s' to %s (#%d) ***\n";
        char msg[128];
        bzero(msg, 128);
        char to_client_name[30];
        get_client_name(cmd_node->to_user_id, to_client_name);
        sprintf(msg, msg_temp, client->name, client->id, last_line, to_client_name, cmd_node->to_user_id);
        broad_cast(client, msg);
        fflush(stdout);
    } else if(cmd_node->pipe_count != 0) {
        int new_pipe_fd[2];
        pipe(new_pipe_fd);
        out_pipe_node = malloc(sizeof(pipe_node_t));
        out_pipe_node->count = cmd_node->pipe_count;
        out_pipe_node->in_fd = new_pipe_fd[0];
        out_pipe_node->out_fd = new_pipe_fd[1];
        out_pipe_node->next_node = NULL;
        insert_pipe_node(&(client->pipe_list), out_pipe_node);

        output_pipe_fd = new_pipe_fd[1];
    }


    pid = fork();
    if(pid == 0) {
        if(input_pipe_fd != -1) {
            // not use stdin
            close(0);
            dup(input_pipe_fd);
            close(input_pipe_fd);
        }

        // out
        if(out_pipe_node != NULL) {
            close(1);
            dup(out_pipe_node->out_fd);
            close(out_pipe_node->out_fd);
        } else if(cmd_node->pipe_to_file == 1) {
            close(1);
            dup(output_pipe_fd);
            close(output_pipe_fd);
        } else if(cmd_node->pipe_to_user == 1) {
            close(1);
            close(2);
            dup(output_pipe_fd);
            dup(output_pipe_fd);
            close(output_pipe_fd);
        } else {
            dup2(client->client_sc_fd, 1);
        }
        execvp(cmd_node->cmd, cmd_node->args);
        exit(-1);

    } else if(pipe_count != 0) {
        int status;
        wait(&status);
        // waitpid(pid, &status, 0);
        if(WEXITSTATUS(status) != 0){
            inscrease_all_pipe_node(client->pipe_list);
            return -1;
        } else {
开发者ID:TakeshiTseng,项目名称:NP-Project2-fork,代码行数:67,代码来源:server.c


示例4: rlimit


//.........这里部分代码省略.........
  }

  /* initialize it to fight lazy allocation */

  fprintf(stderr, "initializing fd array\n");

  for (num_open.rlim_cur = 0;
       num_open.rlim_cur < num_open.rlim_max;
       num_open.rlim_cur++)
    fd[num_open.rlim_cur] = -1;

  sprintf(strbuff, fmt, num_open.rlim_max);
  fprintf(stderr, "trying to open %s file descriptors\n", strbuff);

  /* open a dummy descriptor */

  fd[0] = open(DEV_NULL, O_RDONLY);
  if (fd[0] < 0) {
    sprintf(strbuff, "opening of %s failed", DEV_NULL);
    store_errmsg(strbuff, ERRNO);
    fprintf(stderr, "%s\n", msgbuff);
    free(fd);
    fd = NULL;
    free(memchunk);
    return -7;
  }

  /* create a bunch of file descriptors */

  for (num_open.rlim_cur = 1; 
       num_open.rlim_cur < num_open.rlim_max; 
       num_open.rlim_cur++) {

    fd[num_open.rlim_cur] = dup(fd[0]);

    if (fd[num_open.rlim_cur] < 0) {

      fd[num_open.rlim_cur] = -1;

      sprintf(strbuff1, fmt, num_open.rlim_cur);
      sprintf(strbuff, "dup() attempt %s failed", strbuff1);
      fprintf(stderr, "%s\n", strbuff);

      sprintf(strbuff1, fmt, num_open.rlim_cur);
      sprintf(strbuff, "fds system limit seems close to %s", strbuff1);
      fprintf(stderr, "%s\n", strbuff);

      num_open.rlim_max = num_open.rlim_cur - SAFETY_MARGIN;

      num_open.rlim_cur -= num_open.rlim_max;
      sprintf(strbuff1, fmt, num_open.rlim_cur);
      sprintf(strbuff, "closing %s file descriptors", strbuff1);
      fprintf(stderr, "%s\n", strbuff);

      for (num_open.rlim_cur = num_open.rlim_max;
           fd[num_open.rlim_cur] >= 0;
           num_open.rlim_cur++) {
        close(fd[num_open.rlim_cur]);
        fd[num_open.rlim_cur] = -1;
      }

      sprintf(strbuff, fmt, num_open.rlim_max);
      fprintf(stderr, "shrinking array for %s file descriptors\n", strbuff);

      /* we don't care if we can't shrink it */
开发者ID:SiteView,项目名称:ecc82Server,代码行数:66,代码来源:lib537.c


示例5: 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 = failed_errno;

	/*
	 * 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);
			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);
			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);
fail_pipe:
			error("cannot create pipe for %s: %s",
				cmd->argv[0], strerror(failed_errno));
			errno = failed_errno;
			return -1;
		}
		cmd->err = fderr[0];
	}

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

#if !defined(WIN32) && !defined(AMIGA)
{
	int notify_pipe[2];
	if (pipe(notify_pipe))
		notify_pipe[0] = notify_pipe[1] = -1;

	fflush(NULL);
	cmd->pid = fork();
	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) {
			child_err = dup(2);
			set_cloexec(child_err);
		}
		set_die_routine(die_child);

		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) {
			dup2(fdin[0], 0);
			close_pair(fdin);
		} else if (cmd->in) {
			dup2(cmd->in, 0);
			close(cmd->in);
		}

		if (cmd->no_stderr)
			dup_devnull(2);
		else if (need_err) {
			dup2(fderr[1], 2);
			close_pair(fderr);
//.........这里部分代码省略.........
开发者ID:vidarh,项目名称:Git,代码行数:101,代码来源:run-command.c


示例6: run_file

static void
run_file(const char *filename, uid_t uid, gid_t gid)
{
/* Run a file by spawning off a process which redirects I/O,
 * spawns a subshell, then waits for it to complete and sends
 * mail to the user.
 */
    pid_t pid;
    int fd_out, fd_in;
    int queue;
    char mailbuf[MAXLOGNAME], fmt[49];
    char *mailname = NULL;
    FILE *stream;
    int send_mail = 0;
    struct stat buf, lbuf;
    off_t size;
    struct passwd *pentry;
    int fflags;
    long nuid;
    long ngid;
#ifdef PAM
    pam_handle_t *pamh = NULL;
    int pam_err;
    struct pam_conv pamc = {
	.conv = openpam_nullconv,
	.appdata_ptr = NULL
    };
#endif

    PRIV_START

    if (chmod(filename, S_IRUSR) != 0)
    {
	perr("cannot change file permissions");
    }

    PRIV_END

    pid = fork();
    if (pid == -1)
	perr("cannot fork");
    
    else if (pid != 0)
	return;

    /* Let's see who we mail to.  Hopefully, we can read it from
     * the command file; if not, send it to the owner, or, failing that,
     * to root.
     */

    pentry = getpwuid(uid);
    if (pentry == NULL)
	perrx("Userid %lu not found - aborting job %s",
		(unsigned long) uid, filename);

#ifdef PAM
    PRIV_START

    pam_err = pam_start(atrun, pentry->pw_name, &pamc, &pamh);
    if (pam_err != PAM_SUCCESS)
	perrx("cannot start PAM: %s", pam_strerror(pamh, pam_err));

    pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
    /* Expired password shouldn't prevent the job from running. */
    if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD)
	perrx("Account %s (userid %lu) unavailable for job %s: %s",
	    pentry->pw_name, (unsigned long)uid,
	    filename, pam_strerror(pamh, pam_err));

    pam_end(pamh, pam_err);

    PRIV_END
#endif /* PAM */

    PRIV_START

    stream=fopen(filename, "r");

    PRIV_END

    if (stream == NULL)
	perr("cannot open input file");

    if ((fd_in = dup(fileno(stream))) <0)
	perr("error duplicating input file descriptor");

    if (fstat(fd_in, &buf) == -1)
	perr("error in fstat of input file descriptor");

    if (lstat(filename, &lbuf) == -1)
	perr("error in fstat of input file");

    if (S_ISLNK(lbuf.st_mode))
	perrx("Symbolic link encountered in job %s - aborting", filename);
 
    if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
        (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
        (lbuf.st_size!=buf.st_size))
	perrx("Somebody changed files from under us for job %s - aborting",
		filename);
//.........这里部分代码省略.........
开发者ID:edgar-pek,项目名称:PerspicuOS,代码行数:101,代码来源:atrun.c


示例7: daemonize

void daemonize(const char *cmd)
{
    struct rlimit rlim;
    int fd0, fd1, fd2;
    int i;
    pid_t pid;
    struct sigaction sa;

    if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
        printf("%s: getrlimit error: %s", cmd, strerror(errno));
        exit(1);
    }

    umask(0);

    if ((pid = fork()) < 0) {
        printf("%s: fork error: %s", cmd, strerror(errno));
        exit(1);
    }
    else if (pid != 0) {    /* parent */
        exit(0);
    }
    setsid();   /* child */

    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL) < 0) {
        printf("%s: sigaction SIGHUP error: %s", cmd, strerror(errno));
        exit(1);
    }

    if ((pid = fork()) < 0) {
        printf("%s: fork error: %s", cmd, strerror(errno));
        exit(1);
    }
    else if (pid != 0) {    /* parent again */
        exit(0);
    }

    if (chdir("/") < 0) {
        printf("%s: chdir to / error: %s", cmd, strerror(errno));
        exit(1);
    }

    /* child */
    if (rlim.rlim_max == RLIM_INFINITY)
        rlim.rlim_max = 1024;
    for (i = 0; i < rlim.rlim_max; ++i)
        close(i);

    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);

    openlog(cmd, LOG_CONS, LOG_DAEMON);
    if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
        syslog(LOG_ERR, "unexpected file descriptors: %d, %d, %d",
                fd0, fd1, fd2);
        exit(1);
    }
}
开发者ID:forkhope,项目名称:apue2,代码行数:62,代码来源:uptimesrv.c


示例8: gpgdecode

int gpgdecode(int in_fd, int out_fd)
{
	char passfd_buf[NUMBUFSIZE];
	FILE *fp=passphrasefp();
	int in_dup, out_dup;
	FILE *in_fp, *out_fp;
	struct libmail_gpg_info gi;
	char *argvec[2];
	int i;

	gpginiterr();

	if ((in_dup=dup(in_fd)) < 0 || (in_fp=fdopen(in_dup, "r")) == NULL)
	{
		if (in_dup >= 0)
			close(in_dup);
		fclose(fp);
		enomem();
		return 1;
	}

	if ((out_dup=dup(out_fd)) < 0 || (out_fp=fdopen(out_dup, "w")) == NULL)
	{
		if (out_dup >= 0)
			close(out_dup);
		fclose(in_fp);
		close(in_dup);
		fclose(fp);
		enomem();
		return 1;
	}

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

	gi.gnupghome=GPGDIR;
	if (fp)
	{
		gi.passphrase_fd=libmail_str_size_t(fileno(fp), passfd_buf);
	}

	gi.input_func= read_fd;
	gi.input_func_arg= in_fp;
	gi.output_func= write_fd;
	gi.output_func_arg= out_fp;
	gi.errhandler_func= gpg_error_save;
	gi.errhandler_arg= NULL;

	argvec[0] = "--no-tty";
	argvec[1]=NULL;
	gi.argc=1;
	gi.argv=argvec;

	i=libmail_gpg_decode(LIBMAIL_GPG_UNENCRYPT|LIBMAIL_GPG_CHECKSIGN,
			     &gi);
	fclose(out_fp);
	close(out_dup);
	fclose(in_fp);
	close(in_dup);
	if (fp)
		fclose(fp);

	if (i)
	{
		printf("<div class=\"indent\"><pre style=\"color: red;\">");
		sent_gpgerrtxt();
		printf("</pre></div>\n");
	}
	return (i);
}
开发者ID:mcarbonneaux,项目名称:courier-libs,代码行数:69,代码来源:gpg.c


示例9: uxp_internal_LoadPrintQueue


//.........这里部分代码省略.........
	stAttrValue(stLookup(nodeinfo->Data,"spool_directory"), NULL, &spoolname, 0);

	/** Ok, now open a pipe from the 'lpq' command. **/
	socketpair(AF_UNIX, SOCK_STREAM, 0, pipefd);
	if ((childpid=fork()))
	    {
	    /** Close the child's end of the pipe, since we don't use it in the parent **/
	    close(pipefd[1]);

	    /** Open an fd to the pipe **/
	    fd = fdOpenFD(pipefd[0],O_RDONLY);

	    /** Open an mtlexer session **/
	    lxs = mlxOpenSession(fd, MLX_F_EOL | MLX_F_EOF | MLX_F_IFSONLY);

	    /** Read until we get "Rank" at the beginning of a line. **/
	    while(1)
	        {
		t = mlxNextToken(lxs);
		if (t != MLX_TOK_STRING) 
		    {
		    kill(childpid,SIGKILL);
		    wait(NULL);
		    return pq;
		    }
		str = mlxStringVal(lxs,0);
		while ((t=mlxNextToken(lxs) != MLX_TOK_EOL && t != MLX_TOK_ERROR));
		if (!strcmp(str,"Rank")) break;
		}

	    /** Clean out any existing entries from our internal queue list. **/
	    while(pq->Entries.nItems) 
	        {
		nmFree(pq->Entries.Items[0],sizeof(LprQueueEntry));
		xaRemoveItem(&pq->Entries,0);
		}

	    /** Ok, should be one line per print job now **/
	    for(cnt=0;;)
	        {
		/** Get rank, owner, jobid, filename **/
		if (mlxNextToken(lxs) != MLX_TOK_STRING) break;
		rank = strtoi(mlxStringVal(lxs,0),NULL,10);
		if (mlxNextToken(lxs) != MLX_TOK_STRING) break;
		mlxCopyToken(lxs,user,32);
		if (mlxNextToken(lxs) != MLX_TOK_STRING) break;
		jobid = strtoi(mlxStringVal(lxs,0),NULL,10);
		if (mlxNextToken(lxs) != MLX_TOK_STRING) break;
		mlxCopyToken(lxs,filename,128);

		/** If it isn't our file, skip  to eol and continue looking **/
		if (strncmp(filename, spoolname, strlen(spoolname)))
		    {
		    while ((t=mlxNextToken(lxs) != MLX_TOK_EOL && t != MLX_TOK_ERROR));
		    continue;
		    }

		/** Create the queue entry structure **/
		e = (pLprQueueEntry)nmMalloc(sizeof(LprQueueEntry));
		e->JobID = jobid;
		strcpy(e->User,user);
		e->Percent = 0;
		if (cnt==0) strcpy(e->Status,"Printing");
		else strcpy(e->Status,"Queued");
		strcpy(e->Pathname, filename);
		strcpy(e->Name, strrchr(filename,'/')+1);

		/** Get the file's size and skip to eol. **/
		if (mlxNextToken(lxs) != MLX_TOK_STRING) break;
		e->Size = strtoi(mlxStringVal(lxs,0),NULL,10);
		while ((t=mlxNextToken(lxs) != MLX_TOK_EOL && t != MLX_TOK_ERROR));

		/** Add entry to our queue list **/
		xaAddItem(&pq->Entries, (void*)e);
		cnt++;
		}

	    /** Wait on lpq's completion. **/
	    wait(NULL);
	    }
	else
	    {
	    /** Close the parent's end of the pipe, since we don't use it in the child **/
	    close(pipefd[0]);

	    /** Make the pipe lpq's standard input and output **/
	    close(0);
	    close(1);
	    close(2);
	    dup(pipefd[1]);
	    dup(pipefd[1]);
	    dup(pipefd[1]);

	    /** Execute the lpq process, exit if failed. **/
	    execlp("lpq","lpq","-P",lpname,NULL);
	    _exit(0);
	    }

    return pq;
    }
开发者ID:LightSys,项目名称:centrallix,代码行数:101,代码来源:objdrv_uxprint.c


示例10: setup_tty

static int
setup_tty(struct launcher_direct *launcher, int tty)
{
	struct wl_event_loop *loop;
	struct vt_mode mode = { 0 };
	struct stat buf;
	char tty_device[32] ="<stdin>";
	int ret, kd_mode;

	if (tty == 0) {
		launcher->tty = dup(tty);
		if (launcher->tty == -1) {
			weston_log("couldn't dup stdin: %m\n");
			return -1;
		}
	} else {
		snprintf(tty_device, sizeof tty_device, "/dev/tty%d", tty);
		launcher->tty = open(tty_device, O_RDWR | O_CLOEXEC);
		if (launcher->tty == -1) {
			weston_log("couldn't open tty %s: %m\n", tty_device);
			return -1;
		}
	}

	if (fstat(launcher->tty, &buf) == -1 ||
	    major(buf.st_rdev) != TTY_MAJOR || minor(buf.st_rdev) == 0) {
		weston_log("%s not a vt\n", tty_device);
		weston_log("if running weston from ssh, "
			   "use --tty to specify a tty\n");
		goto err_close;
	}

	ret = ioctl(launcher->tty, KDGETMODE, &kd_mode);
	if (ret) {
		weston_log("failed to get VT mode: %m\n");
		return -1;
	}
	if (kd_mode != KD_TEXT) {
		weston_log("%s is already in graphics mode, "
			   "is another display server running?\n", tty_device);
		goto err_close;
	}

	ioctl(launcher->tty, VT_ACTIVATE, minor(buf.st_rdev));
	ioctl(launcher->tty, VT_WAITACTIVE, minor(buf.st_rdev));

	if (ioctl(launcher->tty, KDGKBMODE, &launcher->kb_mode)) {
		weston_log("failed to read keyboard mode: %m\n");
		goto err_close;
	}

	if (ioctl(launcher->tty, KDSKBMUTE, 1) &&
	    ioctl(launcher->tty, KDSKBMODE, K_OFF)) {
		weston_log("failed to set K_OFF keyboard mode: %m\n");
		goto err_close;
	}

	ret = ioctl(launcher->tty, KDSETMODE, KD_GRAPHICS);
	if (ret) {
		weston_log("failed to set KD_GRAPHICS mode on tty: %m\n");
		goto err_close;
	}

	/*
	 * SIGRTMIN is used as global VT-acquire+release signal. Note that
	 * SIGRT* must be tested on runtime, as their exact values are not
	 * known at compile-time. POSIX requires 32 of them to be available.
	 */
	if (SIGRTMIN > SIGRTMAX) {
		weston_log("not enough RT signals available: %u-%u\n",
			   SIGRTMIN, SIGRTMAX);
		ret = -EINVAL;
		goto err_close;
	}

	mode.mode = VT_PROCESS;
	mode.relsig = SIGRTMIN;
	mode.acqsig = SIGRTMIN;
	if (ioctl(launcher->tty, VT_SETMODE, &mode) < 0) {
		weston_log("failed to take control of vt handling\n");
		goto err_close;
	}

	loop = wl_display_get_event_loop(launcher->compositor->wl_display);
	launcher->vt_source =
		wl_event_loop_add_signal(loop, SIGRTMIN, vt_handler, launcher);
	if (!launcher->vt_source)
		goto err_close;

	return 0;

 err_close:
	close(launcher->tty);
	return -1;
}
开发者ID:ChristophHaag,项目名称:weston,代码行数:95,代码来源:launcher-direct.c


示例11: gpgdomsg

int gpgdomsg(int in_fd, int out_fd, const char *signkey,
	     const char *encryptkeys)
{
	char *k=strdup(encryptkeys ? encryptkeys:"");
	int n;
	int i;
	char *p;
	char **argvec;
	FILE *passfd=NULL;
	char passfd_buf[NUMBUFSIZE];
	struct libmail_gpg_info gi;

	int in_dup, out_dup;
	FILE *in_fp, *out_fp;

	gpginiterr();

	if (!k)
	{
		enomem();
		return 1;
	}

	if ((in_dup=dup(in_fd)) < 0 || (in_fp=fdopen(in_dup, "r")) == NULL)
	{
		if (in_dup >= 0)
			close(in_dup);
		free(k);
		enomem();
		return 1;
	}

	if ((out_dup=dup(out_fd)) < 0 || (out_fp=fdopen(out_dup, "w")) == NULL)
	{
		if (out_dup >= 0)
			close(out_dup);
		fclose(in_fp);
		close(in_dup);
		free(k);
		enomem();
		return 1;
	}

	passfd=passphrasefp();

	n=0;
	for (p=k; (p=strtok(p, " ")) != NULL; p=NULL)
		++n;

	argvec=malloc((n * 2 + 22)*sizeof(char *));
	if (!argvec)
	{
		fclose(out_fp);
		close(out_dup);
		fclose(in_fp);
		close(in_dup);
		free(k);
		enomem();
		return 1;
	}

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

	gi.gnupghome=GPGDIR;
	if (passfd)
	{
		gi.passphrase_fd=libmail_str_size_t(fileno(passfd),
						    passfd_buf);
	}

	gi.input_func= read_fd;
	gi.input_func_arg= in_fp;
	gi.output_func= write_fd;
	gi.output_func_arg= out_fp;
	gi.errhandler_func= gpg_error_save;
	gi.errhandler_arg= NULL;


	i=0;
	argvec[i++] = "--no-tty";
	if (signkey)
	{
		argvec[i++]="--default-key";
		argvec[i++]=(char *)signkey;
	}

	argvec[i++]="--always-trust";

	for (p=strcpy(k, encryptkeys ? encryptkeys:"");
	     (p=strtok(p, " ")) != NULL; p=NULL)
	{
		argvec[i++]="-r";
		argvec[i++]=p;
	}
	argvec[i]=0;
	gi.argc=i;
	gi.argv=argvec;

	i=libmail_gpg_signencode(signkey ? 1:0,
				 n > 0 ? LIBMAIL_GPG_ENCAPSULATE:0,
//.........这里部分代码省略.........
开发者ID:mcarbonneaux,项目名称:courier-libs,代码行数:101,代码来源:gpg.c


示例12: main


//.........这里部分代码省略.........
    */
   if (gethostname(my_hostname, sizeof(my_hostname) - 1) < 0) {
      Pmsg1(0, _("Fatal gethostname error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
   if ((hp = gethostbyname(my_hostname)) == NULL) {
      Pmsg2(0, _("Fatal gethostbyname for myself failed \"%s\": ERR=%s\n"), my_hostname,
         strerror(errno));
      exit(1);
   }
   strcpy(my_hostname, hp->h_name);
   Dmsg1(20, "My hostname is: %s\n", my_hostname);

   /*
    *  Determine from address.
    */
   if (from_addr == NULL) {
#if defined(HAVE_WIN32)
      DWORD dwSize = UNLEN + 1;
      LPSTR lpszBuffer = (LPSTR)alloca(dwSize);

      if (GetUserName(lpszBuffer, &dwSize)) {
         sprintf(buf, "%[email protected]%s", lpszBuffer, my_hostname);
      } else {
         sprintf(buf, "[email protected]%s", my_hostname);
      }
#else
      if ((pwd = getpwuid(getuid())) == 0) {
         sprintf(buf, "userid-%[email protected]%s", (int)getuid(), my_hostname);
      } else {
         sprintf(buf, "%[email protected]%s", pwd->pw_name, my_hostname);
      }
#endif
      from_addr = bstrdup(buf);
   }
   Dmsg1(20, "From addr=%s\n", from_addr);

   /*
    *  Connect to smtp daemon on mailhost.
    */
hp:
   if ((hp = gethostbyname(mailhost)) == NULL) {
      Pmsg2(0, _("Error unknown mail host \"%s\": ERR=%s\n"), mailhost,
         strerror(errno));
      if (strcasecmp(mailhost, "localhost") != 0) {
         Pmsg0(0, _("Retrying connection using \"localhost\".\n"));
         mailhost = "localhost";
         goto hp;
      }
      exit(1);
   }

   if (hp->h_addrtype != AF_INET) {
      Pmsg1(0, _("Fatal error: Unknown address family for smtp host: %d\n"), hp->h_addrtype);
      exit(1);
   }
   memset((char *)&sin, 0, sizeof(sin));
   memcpy((char *)&sin.sin_addr, hp->h_addr, hp->h_length);
   sin.sin_family = hp->h_addrtype;
   sin.sin_port = htons(mailport);
#if defined(HAVE_WIN32)
   if ((s = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0)) < 0) {
      Pmsg1(0, _("Fatal socket error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
#else
开发者ID:halgandd,项目名称:bacula,代码行数:67,代码来源:bsmtp.c


示例13: main


//.........这里部分代码省略.........
                {
                    printf("TOKEN %d: %s\n",j,savedTokens[j]);
                    j++;
                } */
        		//record command in history list (GNU readline history ?)
                int std_out;
                if(no_of_commands!=-1)
                {
            		if ( (cmd!=NULL) && isBuiltInCommand(cmd)==1 )
                    {
                            if(redirectFlag!=0)
                            {
                                executeRedirect(cmd,com,redirectFlag);
                            }
                            if(outfile!=0)
                            {
                                int fd1;
                                if(outfile==1)
                                {
                                    fd1=open(output,O_CREAT|O_RDWR|O_TRUNC,00666);
                                    lseek(fd1, 0, SEEK_SET);
                                }
                                else if(outfile==2)
                                {
                                    fd1=open(output,O_APPEND|O_CREAT|O_RDWR,00666);
                                }
                                if(fd1==-1)
                                {
                                    fprintf(stderr, "Can't open file %s for output!\n",output);
                                    memset(output, 0, 10);
                                    outfile=0;
                                    continue;
                                }
                                std_out=dup(1);
                                dup2(fd1,STDOUT_FILENO);
                                close(fd1);
                                memset(output, 0, 10);
                                outfile=0;
                            }
                            if(infile==3)
                            {
                                int fd2;
                                fd2=open(inputfile,O_RDWR,00666);
                                if(fd2==-1)
                                {
                                    fprintf(stderr, "Can't open file for input! 4\n");
                                    memset(inputfile, 0, 10);
                                    infile=0;
                                    continue;
                                }
                                dup2(fd2,STDIN_FILENO);
                                close(fd2);
                                memset(inputfile, 0, 10);
                                infile=0;
                            }
                            job_no++;
                            addJob(0,cmd,0,job_no);
                            executeBuiltInCommand(cmd,savedTokens,no_of_tokens,homedir);
                            dup2(std_out,1);
                    }
                    else
                    {
                        if((com!=NULL) && isBackgroundJob(com)==1)
                        {
                            savedTokens[no_of_tokens]=NULL;
                        }
开发者ID:SaumyaRawat,项目名称:Shell,代码行数:67,代码来源:shell.c


示例14: executePipe

int executePipe( int no_of_pipes, char *com, int redirectFlag,char *homedir)
{
    pc *pcmd=malloc(100 * sizeof(pc));
    int fd[2];
    int isFirstPipe=1;
    int count = 0;
    char *commandline=malloc(1024*sizeof(char));
    strcpy(commandline,com);

    char *command=malloc(1024*sizeof(char));
    char **argv=malloc ( 100 * sizeof(char)); //Number of tokens there can be
    char *token=malloc(1024*sizeof(char));
    int i=0,j=0;
    command = strtok ( com,"|");  //first command
    while( command!=NULL)
    {
        pcmd[i].argv=command;
        pcmd[i].redirectFlag=isRedirect(command);
        command = strtok (NULL, "|");
        i++;
    }
    //Tokenise command for execution
    //parseCommand(pcmd[0].argv,argv);

    int in=0;
    for(i=0;i<no_of_pipes;i++)
    {
        pipe(fd);
        spawn_proc(in,fd[1],pcmd[i],pcmd[i].redirectFlag,homedir);
        close(fd[1]);
        in=fd[0];
    }
    if(in!=0)
        dup2(in,0);
    //last command
    infile=0;
    outfile=0;
    int random=isRedirect(pcmd[i].argv);
    int no_of_tokens=parseCommand(pcmd[i].argv,argv,pcmd[i].redirectFlag);
    int std_out=dup(1);
    if(outfile!=0)
    {
        int fd1;
        if(outfile==1)
        {
            fd1=open(output,O_CREAT|O_RDWR|O_TRUNC,00666);
            lseek(fd1, 0, SEEK_SET);
        }
        else if(outfile==2)
        {
            fd1=open(output,O_APPEND|O_CREAT|O_RDWR,00666);
        }
        if(fd1==-1)
        {
            fprintf(stderr, "Can't open file for output 1!\n");
            memset(output, 0, 10);
            outfile=0;
            return;
        }
        dup2(fd1,STDOUT_FILENO);
        close(fd1);
        memset(output, 0, 10);
        outfile=0;
        //redirectFlag=0;
    }
    if(infile==3)
    {
        int fd2;
        fd2=open(inputfile,O_RDWR,00666);
        if(fd2==-1)
        {
            fprintf(stderr, "Can't open file for input! 3\n");
            memset(inputfile, 0, 10);
            infile=0;
            return;
        }
        dup2(fd2,STDIN_FILENO);
        close(fd2);
        memset(inputfile, 0, 10);
        infile=0;
        //redirectFlag=0;
    }

    if(isBuiltInCommand(argv[0])==1)
    {
        job_no++;
        addJob(0,argv[0],0,job_no);
        executeBuiltInCommand(argv[0],argv,no_of_tokens,homedir);
        _exit(1);
        dup2(std_out,1);
        return(0);
    }
    else
        return(execvp(argv[0],argv));
}
开发者ID:SaumyaRawat,项目名称:Shell,代码行数:95,代码来源:shell.c


示例15: sourceFile


//.........这里部分代码省略.........
            //// C shell script //// 
            
            // Run the command
            fprintf(file, "source %s\n\n", filename);
            
            fprintf(file, "echo '%s'\n\n", SIRE_ENV_TAG);
            fprintf(file, "%s %s\n\n", envProg, envArg);
         }
         
         else if ((!strncmp(shell, SH_NAME,   sizeof(SH_NAME)-1)) ||
                  (!strncmp(shell, KSH_NAME,  sizeof(KSH_NAME)-1)) ||
                  (!strncmp(shell, RKSH_NAME, sizeof(RKSH_NAME)-1)) ||
                  (!strncmp(shell, BASH_NAME, sizeof(BASH_NAME)-1)))
         {
            //// Bourn/Korn shell script //// 
            
            fprintf(file, ". %s\n", filename);
            
            fprintf(file, "echo '%s'\n\n", SIRE_ENV_TAG);
            fprintf(file, "%s %s\n\n", envProg, envArg);
         }
         
         else
         {
            // Unknown script type
            
            printE("Unsupported shell [%s]\n", shell);
            fclose(file);
            unlink (script);
            return(1);  //// BAILING OUT ////
         }
         
         fclose(file);
            
         chmod (script, S_IRWXU | S_IRWXG);
         Tenv::appUnsetStd();
   
         // Right I admit it this is cut and paste with a bit re-hacking
         // Run the script and capture the environment variable settings
         // that 'sirenv' passes back.
         {
             char buff[1024];
             int  pipes[2];
 
             if (0 == pipe(pipes))
             {
                char  *p;
                FILE  *fd;
                int    tmpStd = -1;

                // Configure the pipes for the sub-process
                tmpStd = dup(1);   // Take a copy of standard out
                dup2(pipes[1], 1); // Make the pipe standard out
                close(pipes[1]);
 
                // Spawn the sub process
                MYspawnve(MY_NOWAIT, script, (const char**)globalArgv, Tenv::appGetEnvp());
 
                // Reset the pipes
                dup2(tmpStd, 1);             // Put back standard out
                close(tmpStd);               // Close the spare copy
                fd = fdopen(pipes[0], "r");  // Read the other end
                
                while (NULL != (p = fgets(buff, sizeof(buff), fd)))
                {
                    while (isspace(*p)) p++;
                    
                    if ('\0' == *p)
                    {
                        // Pass through the blank lines
                        printf("%s", buff);
                    }
                    else if (!strncmp(p, SIRE_ENV_TAG, sizeof(SIRE_ENV_TAG)-1))
                    {
                        // Read the environment
                        // The tag marks the start of the environment
                        
                        // Clear any output
                        fflush(stdout);
                        
                        // Read the environment
                        Tenv::setApp(fd);
                    }
                    else
                    {
                        // Pass through any other output
                        printf("%s", buff);
                    }
                }
                
                fclose(fd);
             }
         }
      
         unlink (script);
      }
   }
   
   return (0);
}
开发者ID:LaMaisonOrchard,项目名称:Sire,代码行数:101,代码来源:sys.cpp


示例16: main

//This is the main loop that runs the shell and takes in the commands
int main(int argc, char const *argv[])
{
    char *input;
    pid_t childpid, pipeChild;
    int status, execStatus, commandTwo;
    int runInBG = 0, redirToFile = 0, pipefd[2];
    struct sigaction childFinished;

    childFinished.sa_sigaction = endSignal;

    input = malloc(sizeof(char)*50);
    printf("Welcome to MaSh, enter a command.\n");
    printf(">");
    fgets(input,50,stdin);
    sigaction(SIGCHLD, &childFinished, NULL);
    while(strcmp(input,"exit\n") != 0) {
        runInBG = 0;
        redirToFile = 0;
        commandTwo = 0;
        char **args = calloc(10,sizeof(char*));
        //parse user input into argument array
        status = parseInput(input,args);
        if (status > 1)
            runInBG = runInBackground(args,status);
        if (status > 2)
            redirToFile = redirectToFromFile(runInBG,args,status, &commandTwo);
        childpid = fork();
        if (childpid >= 0) { //fork success
            if (childpid == 0) {
                if (redirToFile == 1) {
                    execStatus = writeOptToFile(runInBG,args,status);
                }
                else if (redirToFile == 2) {
                    execStatus = readIptFromFile(runInBG,args,status);
                }
                else if (redirToFile == 3) {
                    //create pipe
                    if (pipe(pipefd) == -1) {
                        printf("Pipe failed.\n");
                    }
                    pipeChild = fork();
                    if (pipeChild >= 0) {
                        //read from the pipe
                        if (pipeChild == 0) {
                            close(1);
                            dup(pipefd[1]);
                            close(pipefd[0]);
                            execStatus = execvp(*args,args);
                            exit(0);
                        }
                        //write to the pipe
                        else {
                            close(0);
                            dup(pipefd[0]);
                            close(pipefd[1]);
                            execStatus = execvp(args[commandTwo],args+commandTwo);
                        }
                    }
                    else {
                        perror("Fork failed.");
                        exit(-1);
                    }
                }
                else {
                    //this is supposed to make the output of commands not appear on screen, it doesnt work though
                    if (runInBG == 1) {
                        setpgid(0,0);
                    }
                    execStatus = execvp(*args,args);
                }
                if (execStatus < 0) {
                    printf("Command \"%s\" not found.\n", input);
                }
                exit(0);
            }
            else {
                //may not need to do this
                if (runInBG == 1) {
                    waitpid(-1,&status,WNOHANG | WUNTRACED);
                    runInBG = 0;
                }
                else
                    waitpid(childpid,&status,0);
            }
        }
        else {
            printf("Fork failed.\n");
        }
        printf(">");
        fgets(input,50,stdin);
        free(args);
    }
    kill(childpid,SIGKILL);
    printf("logout\n");
    printf("\n");
    printf("[Process completed]\n");
    exit(0);
}
开发者ID:sampson7185,项目名称:3110-A1,代码行数:99,代码来源:myShell.c


示例17: Dnext

Tpipe::Tpipe(char const *comm, int read, Tenv *env) : Dnext(Dhead), Dscript("")
{
   Dhead = this;
   Dpid  = -1;
   Dfd   = NULL;
   
   if (DsetClear) {DsetClear = FALSE; atexit(Tpipe::clear);}
   
   while (isspace(*comm)) comm++;
   
   int pipes[2];
   
   Dscript = makeScript(comm);
      
   if ((0 != strlen(comm)) && (0 == pipe(pipes)))
   {
      char **localEnv;
      char  *(argv[2]);
      int    tmpStd = -1;
      
      if (read)
      {
         tmpStd = dup(1);   // Take a copy of standard out
         dup2(pipes[1], 1); // Make the pipe standard out
         close(pipes[1]);
      }
      else
      {
         tmpStd = dup(1);   // Take a copy of standard in
         dup2(pipes[0], 0); // Make the pipe standard in
         close(pipes[0]);
      }
            
      // Get the environment
      if (NULL == env)
          localEnv = Tenv::appGetEnvp();
      else
          localEnv = env->getEnvp();

      // Set up the arguments to the call
      argv[0] = (char*)malloc(strlen((char const*)Dscript)+1);
      strcpy(argv[0], (char const*)Dscript);
      argv[1] = NULL;
      
      // Spawn the sub process
      Dpid = MYspawnve(MY_NOWAIT, (char*)(char const*)Dscript, (const char**)argv, localEnv);
      
      // Free the allocated space
      free(argv[0]);
      
      if (read)
      {
         dup2(tmpStd, 1);             // Put back standard out
         close(tmpStd);               // Close the spare copy
         Dfd = fdopen(pipes[0], "r"); // Read the other end
      }
      else
      {
         dup2(tmpStd, 0);             // Put back standard in
         close(tmpStd);               // Close the spare copy
         Dfd = fdopen(pipes[1], "w"); // Write the other end
  

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ dup2函数代码示例发布时间:2022-05-30
下一篇:
C++ dumpregs函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap