openssh中pipe使用的一个样例

scp.c

/*
 * This function executes the given command as the specified user on the
 * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
 * assigns the input and output file descriptors on success.
 */

int
do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
{
    int pin[2], pout[2], reserved[2];

    if (verbose_mode)
        fprintf(stderr,
            "Executing: program %s host %s, user %s, command %s\n",
            ssh_program, host,
            remuser ? remuser : "(unspecified)", cmd);

    /*
     * Reserve two descriptors so that the real pipes won't get
     * descriptors 0 and 1 because that will screw up dup2 below.
     */
    if (pipe(reserved) < 0)
        fatal("pipe: %s", strerror(errno));

    /* Create a socket pair for communicating with ssh. */
    if (pipe(pin) < 0)
        fatal("pipe: %s", strerror(errno));
    if (pipe(pout) < 0)
        fatal("pipe: %s", strerror(errno));

    /* Free the reserved descriptors. */
    close(reserved[0]);
    close(reserved[1]);

    signal(SIGTSTP, suspchild);
    signal(SIGTTIN, suspchild);
    signal(SIGTTOU, suspchild);

    /* Fork a child to execute the command on the remote host using ssh. */
    do_cmd_pid = fork();
    if (do_cmd_pid == 0) {
        /* Child. */
        close(pin[1]);
        close(pout[0]);
        dup2(pin[0], 0);
        dup2(pout[1], 1);
        close(pin[0]);
        close(pout[1]);

        replacearg(&args, 0, "%s", ssh_program);
        if (remuser != NULL) {
            addargs(&args, "-l");
            addargs(&args, "%s", remuser);
        }
        addargs(&args, "--");
        addargs(&args, "%s", host);
        addargs(&args, "%s", cmd);

        execvp(ssh_program, args.list);
        perror(ssh_program);
        exit(1);
    } else if (do_cmd_pid == -1) {
        fatal("fork: %s", strerror(errno));
    }
    /* Parent.  Close the other side, and return the local side. */
    close(pin[0]);
    *fdout = pin[1];
    close(pout[1]);
    *fdin = pout[0];
    signal(SIGTERM, killchild);
    signal(SIGINT, killchild);
    signal(SIGHUP, killchild);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值