2017-05-15 5 views
-1

ソースコード:整数配列をパイプに書き込む方法と、最初からそれを読み取る方法は?

#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); 

これは可能ですか?そうでなければ、私は構造体を使用します。

+4

コードを見やすく書式設定してください。 –

+0

配列全体をパイプに書き込む必要があります。しかし、なぜこれにパイプを使いたいのですか?これを読んでください:[XY問題](http://xyproblem.info/)。 –

+0

あなたは1つのintを書いたり読んだりするいくつかのコードを書いているようですね?配列のためにそれを繰り返すことは、ループを使用したそれの拡張です。 –

答えて

1

パイプ経由でintの2つの配列を連結します。

#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); 
    } 
} 
+0

助けてくれてありがとう、それは私のせいだった、前回は間違っていた、今質問を修正した。この問題を解決するために私を助けることができますか? – zarnilord

関連する問題