使用管道通过父母和孩子之间的整数值 [英] Using pipe to pass integer values between parent and child

查看:177
本文介绍了使用管道通过父母和孩子之间的整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何正确使用管道()来传递两个进程之间的整数值有点糊涂了。

I'm a little confused on how to properly use pipe() to pass integer values between two processes.

在我的节目,我先创建一个管道,然后我叉它。我认为我有二管呢?

In my program I first create a pipe, then I fork it. I assume I have "Two" pipes then?

据我了解,这是我的任务。
我的父母经过一个for循环检查的整数值的i一定的操作,增加一个计数变量,并保存价值到一个数组。每次检查后,我的父母应该通过管道传递一个整数值,我我的孩子。我的孩子然后使用该整数值,确实对一些值检查,应增加一个计数变量,并将结果保存在[共享?]数组。最终,孩子应该回到它的最终计父,谁再打印出两项罪名,而共享阵列。

From what I understand, this is my assignment. My parent goes through a for loop checking an integer value "i" for a certain operation, increases a count variable, and saves value into an array. After each check my parent should pass an integer value, "i" to my child through a pipe. My child then uses that integer value, does some check on the value, and should increase a count variable, and save the result in a [shared?] array. Eventually; the child should return it's final count to the parent, who then prints out the two counts, and the "Shared" array.

- >我不知道我需要有一个共享的数组或对结果都保存。我可能只需要数 - 作业含糊不清,我等待教授的响应。也;我甚至可以做的进程间共享的阵列?这听起来似乎有些问题,给我一个开始。

-> I'm not sure I need to have a shared array or to save the results at all. I may only need the counts - the homework was ambiguous and I'm awaiting a response from the professor. Also; can I even do a shared array between processes? It sounds like a start of some problem to me.

- >这里是我的问题:
一;我该如何使用管道整数?我只看到他们的字符数组和previous答案似乎并不认为这是可能或法律..?我不确定。有没有解决,我能找到它。

-> Here are my questions: One; how do I use pipes for integers? I've only seen them for character arrays and previous answers don't seem to think this is possible or legal..? I'm not sure. There was no resolution that I could find on it.

- >如何使用单向管道整数传递给孩子?并有孩子的回报的东西吗?我不知道我是如何能......两个管道进行区分。我知道[或认为我知道]我必须关闭每个管的一个未使用的部分,以避免一些模糊的问题。

-> How do I use a unidirectional pipe to pass integers to a child? And have the child return something? I'm not sure how I'm able to... differentiate between the two pipes. I do "know" [or think I know] that I have to close one unused portion of each pipe to avoid "Some vague problem".

很抱歉的愚蠢的问题;我没有被教导的进程(除了叉)或管道(所有),但在这个类 - !所以我真的不知道从哪里开始。

Sorry for the dumb questions; I haven't been taught processes (aside from fork) or pipes (at all) yet in this class - so I'm not really sure where to start!

我的code的继承人部分 - 它不是pretty和它不工作,我不希望它。它更像是一个外壳占位符。一旦我弄清楚如何使用管道 - 我可能会做code有意义

Heres parts of my code - it's not pretty and it doesn't work and I don't expect it to. It's more of a shell placeholder. Once I figure out how to use a pipe - I'd Probably make the code make sense.

int main(void)
{
int fd[2];
pid_t childpid;
pid_t parentpid;
int i;
int threecount = 0;
int fivecount = 0;;
int results [MAXSIZE];

parentpid = getpid(); //Get current process ID number

pipe(fd);
childpid = fork(); 

if(childpid == 0){
close(fd[0]); //Closing this for some other reason

}
int j = 0;

if(childpid > 0)
close(fd[1]); //Closing this for some reason


if( childpid == -1 )
{
    perror("Failed to fork\n");
    return 1;
}
if (childpid > 0)
{
    for(i = 1; i < MAXSIZE;i++)
    {
        if(i % 5 == 0)
        {
            fivecount++;
            i = results[j];
            j++; 
            wait(NULL);
        }
    }
}
else if (childpid == 0)
    {
        if(i % 3 == 0) //This i here should probably be the i value above, piped to the child
        {
            threecount++;
            i = results[j];  //This should be part of th pipe
            j++;    //Trying to keep count of that shared array, not really the right way to do it though.
        }

    }
    printf("%d  %d  \n", fivecount,threecount);
    return 0;

}

推荐答案

这大约是跛脚(没有错误检查,顺便说一句),我可以鼓起了使用管道从父送INT到一个子进程的样本,那里的孩子从叉子推出()。它变得更为复杂(显然)发送的的接收数据,但我不能为你做的所有的。这正好叉,并等待一个int(实际上是由一个int使用的字节数)从孩子。

This is about as lame (and no error checking, btw) a sample as I can muster for using a pipe to send int from a parent to a child process, where the child was launched from fork(). It gets more complicated (obviously) for sending and receiving data, but i can't do everything for you. This just forks and waits for an int (actually, the number of bytes that are used by an int) from the child.

更新:添加这一项之后发送+响应双向通信的例子。看到第二个code房源的详细信息。

Update: Added send+response two-way communication example after this one. See the second code listing for more information.

希望它帮助。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int fd[2];
    int val = 0;

    // create pipe descriptors
    pipe(fd);

    // fork() returns 0 for child process, child-pid for parent process.
    if (fork() != 0)
    {
        // parent: writing only, so close read-descriptor.
        close(fd[0]);

        // send the value on the write-descriptor.
        val = 100;
        write(fd[1], &val, sizeof(val));
        printf("Parent(%d) send value: %d\n", getpid(), val);

        // close the write descriptor
        close(fd[1]);
    }
    else
    {   // child: reading only, so close the write-descriptor
        close(fd[1]);

        // now read the data (will block)
        read(fd[0], &val, sizeof(val));
        printf("Child(%d) received value: %d\n", getpid(), val);

        // close the read-descriptor
        close(fd[0]);
    }
    return 0;
}

输出:

Parent(5943) send value: 100
Child(5945) received value: 100


更新:扩展使用两个管套包括发送+响应


Update: Expanded to include send+response using two pipe sets

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// some macros to make the code more understandable
//  regarding which pipe to use to a read/write operation
//
//  Parent: reads from P1_READ, writes on P1_WRITE
//  Child:  reads from P2_READ, writes on P2_WRITE
#define P1_READ     0
#define P2_WRITE    1
#define P2_READ     2
#define P1_WRITE    3

// the total number of pipe *pairs* we need
#define NUM_PIPES   2

int main(int argc, char *argv[])
{
    int fd[2*NUM_PIPES];
    int val = 0, len, i;
    pid_t pid;

    // create all the descriptor pairs we need
    for (i=0; i<NUM_PIPES; ++i)
    {
        if (pipe(fd+(i*2)) < 0)
        {
            perror("Failed to allocate pipes");
            exit(EXIT_FAILURE);
        }
    }

    // fork() returns 0 for child process, child-pid for parent process.
    if ((pid = fork()) < 0)
    {
        perror("Failed to fork process");
        return EXIT_FAILURE;
    }

    // if the pid is zero, this is the child process
    if (pid == 0)
    {
        // Child. Start by closing descriptors we
        //  don't need in this process
        close(fd[P1_READ]);
        close(fd[P1_WRITE]);

        // used for output
        pid = getpid();

        // wait for parent to send us a value
        len = read(fd[P2_READ], &val, sizeof(val));
        if (len < 0)
        {
            perror("Child: Failed to read data from pipe");
            exit(EXIT_FAILURE);
        }
        else if (len == 0)
        {
            // not an error, but certainly unexpected
            fprintf(stderr, "Child: Read EOF from pipe");
        }
        else
        {
            // report what we received
            printf("Child(%d): Received %d\n", pid, val);

            // now double it and send it back
            val *= 2;

            printf("Child(%d): Sending %d back\n", pid, val);
            if (write(fd[P2_WRITE], &val, sizeof(val)) < 0)
            {
                perror("Child: Failed to write response value");
                exit(EXIT_FAILURE);
            }
        }

        // finished. close remaining descriptors.
        close(fd[P2_READ]);
        close(fd[P2_WRITE]);

        return EXIT_SUCCESS;
    }

    // Parent. close unneeded descriptors
    close(fd[P2_READ]);
    close(fd[P2_WRITE]);

    // used for output
    pid = getpid();

    // send a value to the child
    val = 42;
    printf("Parent(%d): Sending %d to child\n", pid, val);
    if (write(fd[P1_WRITE], &val, sizeof(val)) != sizeof(val))
    {
        perror("Parent: Failed to send value to child ");
        exit(EXIT_FAILURE);
    }

    // now wait for a response
    len = read(fd[P1_READ], &val, sizeof(val));
    if (len < 0)
    {
        perror("Parent: failed to read value from pipe");
        exit(EXIT_FAILURE);
    }
    else if (len == 0)
    {
        // not an error, but certainly unexpected
        fprintf(stderr, "Parent(%d): Read EOF from pipe", pid);
    }
    else
    {
        // report what we received
        printf("Parent(%d): Received %d\n", pid, val);
    }

    // close down remaining descriptors
    close(fd[P1_READ]);
    close(fd[P1_WRITE]);

    // wait for child termination
    wait(NULL);

    return EXIT_SUCCESS;
}

输出

Parent(2794): Sending 42 to child
Child(2797): Received 42
Child(2797): Sending 84 back
Parent(2794): Received 84

这篇关于使用管道通过父母和孩子之间的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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