如何将整数数组写入管道以及如何从中读取第一个?

时间:2017-05-15 08:41:38

标签: c linux fork

源代码:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


int main(){
    int fd1[2];
    int sample[] = {1,2,3,4};
    int input[] ={5 , 6, 7,8};
    pid_t p;

    if (pipe(fd1)==-1)return 1;
    if (pipe(fd2)==-1) return 1;

    write(fd1[1], input, sizeof(input)+1);
    write(fd1[1], sample, sizeof(sample)+1);
    close(fd1[1]);
    char concat[100];
    read(fd1[0],concat,100);
    int i=0;
    for(i;i<sizeof(concat);i++){
            printf("%i ",concat[i]);

}
        printf("\n");

}

我想在管道上编写数组,之后我只想读出第一个数组,而不是代码中的整个管道:

read(fd1[0],concat,100);

这可能吗?如果不是,我将使用结构。

1 个答案:

答案 0 :(得分:1)

通过管道连接两个int数组。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


int main()
{
    int fd1[2];
    int fd2[2];

    int sample[] = {1,2,3,4};
    int input[] ={5 , 6, 7,8};
    pid_t p;

    if (pipe(fd1)==-1)return 1;
    if (pipe(fd2)==-1) return 1;

    p = fork();

    if (p < 0) return 1;

    // Parent process
    else if (p > 0)
    {
        int concat[100];
        close(fd1[0]);
        write(fd1[1], input, sizeof(input)+1);
        close(fd1[1]);

        wait(NULL);

        close(fd2[1]);
        read(fd2[0], concat, 100);

        printf(" %i", concat[0]);
        printf(" %i", concat[1]);
        printf(" %i", concat[2]);
        printf(" %i", concat[3]);

        close(fd2[0]);
    }

    // child process
    else
    {
        close(fd1[1]);
        char concat[100];
        read(fd1[0], concat, 100);
        int k = sizeof(concat);
        int i;
        for (i=0; i<sizeof(sample); i++)
            concat[k++] = sample[i];

        concat[k] = '\0';

        close(fd1[0]);
        close(fd2[0]);

        write(fd2[1], concat, sizeof(concat)+1);
        close(fd2[1]);
        exit(0);
    }
}