如何写信给管叉? [英] How to write to the pipe fork?

查看:179
本文介绍了如何写信给管叉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的功能,通过fork和execvp执行命令。我的脚本,我叉推出用于监听输入数据。我怎样才能将数据发送到MYSCRIPT?

  INT external_command()
{    INT工艺流程图[2];
    如果(管道(工艺流程图)℃,)
        返回-1;    如果((uproc.pid =叉())== -1)
        返回-1;    如果(uproc.pid == 0){
        / * *子/        为const char * argv的[4];
        INT I = 0;
        的argv [我++] =/ bin / sh的;
        的argv [我++] =myscript.sh;
        的argv [我++] = NULL;        关闭(工艺流程图[0]);
        dup2(工艺流程图[1],1);
        关闭(工艺流程图[1]);        execvp(的argv [0],(字符**)的argv);
        出口(ESRCH);    }否则如果(uproc.pid℃,)
        返回-1;    / *母公司* /
    关闭(工艺流程图[1]);    INT状态;
    而(等待(安培;!状态)= uproc.pid){
        DD(等待孩子退出);
    }    字符缓冲区[64];
    ssiz​​e_t供rxed;
    字符* C;
    INT吨;    //从前叉管阅读
    *值= NULL;
    而((rxed =读(工艺流程图[0],缓冲液,的sizeof(缓冲液)))0){
        如果(*值)
            T = asprintf(和C,%s%* S,*值(INT)rxed,缓冲区);
        其他
            T = asprintf(和C,%*第,(int)的rxed,缓冲液);        如果(T == -1)返回-1;        免费(*值);
        *值=的strdup(C);
        免费(C);
    }
    //如何写入管道叉?
}


解决方案

一个管道是单向的。呼叫管道两次,得到一对文件描述符从孩子读数据(因为你已经有了),另一个发送数据到孩子(这将是新的) 。你需要做同样的 dup2 因为你已经在做,以关闭魔法设置一个新的管道作为标准输入的孩子。

I have the following function which execute command via fork and execvp. my script that I launch in fork is listening for input data. How I can send data to myscript?

int external_command()
{

    int pfds[2];
    if (pipe(pfds) < 0)
        return -1;

    if ((uproc.pid = fork()) == -1)
        return -1;

    if (uproc.pid == 0) {
        /* child */

        const char *argv[4];
        int i = 0;
        argv[i++] = "/bin/sh";
        argv[i++] = "myscript.sh";
        argv[i++] = NULL;

        close(pfds[0]);
        dup2(pfds[1], 1);
        close(pfds[1]);

        execvp(argv[0], (char **) argv);
        exit(ESRCH);

    } else if (uproc.pid < 0)
        return -1;

    /* parent */
    close(pfds[1]);

    int status;
    while (wait(&status) != uproc.pid) {
        DD("waiting for child to exit");
    }

    char buffer[64];
    ssize_t rxed;
    char *c;
    int t;

    //read from fork pipe
    *value = NULL;
    while ((rxed = read(pfds[0], buffer, sizeof(buffer))) > 0) {
        if (*value)
            t = asprintf(&c, "%s%.*s", *value, (int) rxed, buffer);
        else
            t = asprintf(&c, "%.*s", (int) rxed, buffer);

        if (t == -1) return -1;

        free(*value);
        *value = strdup(c);
        free(c);
    }
    // how to write to the pipe fork?
}

解决方案

A pipe is unidirectional. Call pipe twice, to get one pair of file descriptors for reading data from the child (as you already have) and another to sent data to the child (which will be new). You'll need to do the same sort of dup2 and close magic as you're already doing, in order to set up that new pipe as stdin for the child.

这篇关于如何写信给管叉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆