2016-06-27 13 views
0

私は父と子プロセスの間にパイプを作成しようとしています。このパイプ内の 、子プロセスはデータを書き、父はそれを読み込んで印刷します。 なぜか分かりませんが、大きな文字列を入力するとデータが間違ってしまいます。 バッファーの大きさだと思っていますが、それを修正することはできません。父と子のプロセス間にパイプを作成する

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

/* in this code i will make a child process with fork command 
then i will create pipe using pipe commands. 
i will transfer data from the child process to the father process 
omriziner code 
*/ 

void main(int argc,char *argv[]) 
{ 
    if(argc < 2){ 
     printf("prototype error \n<Enter any data you wana write> \n"); 
     return; 
    } 

    int fd[2]; // creating array with 2 places for 2 fd'stdio 
    // fd[0] is set to read file in the pipe 
    //fd[1] is set to write file in the pipe 
    int piperes; 
    pid_t childpid; 
    char buff[5]; 
    char * data = "learning to the exam"; 
    printf("father pid %d:\n",getpid()); 
    printf ("size of data is %d \n",(int)sizeof(argv[1])); 
    printf ("size of buff is %d \n",(int)sizeof(buff)); 
    piperes = pipe(fd); 
    if(piperes < 0){ 
     perror("PIPE ERR"); 
     exit(1); 
    } 
    printf("Pipe succeed \n"); 
    if((childpid = fork()) == -1){ // fork will create a child process 
     perror("FORK ERR"); 
     exit(1); 
    } 
// when fork suceed - the pid of the child will return in the parent and 0 will return in the child 
// when fork fail - the pid will be -1 

    printf("Fork succeed, fork return is %d and process pid is %d :\n",childpid,getpid()); 

    if(childpid == 0){ // if pid zero , wer in the child prcs 
     close(fd[0]);  
     write(fd[1],argv[1],sizeof(argv[1])); // send data to the write fd of the pipe 
     printf("data was written to fd[1] by pid : %d \n",getpid()); 
     exit(0); 
    } 
    else{ // in this case, we're in the father process 
     close(fd[1]); 
     read(fd[0],buff,sizeof(argv[1])+1); 
     printf("Recived data is ''%s''", buff); 
     printf("By pid : %d \n",getpid()); 
     exit(1); 
    } 
} 

答えて

1
sizeof(argv[1]) 

これは、あなたがそれがないと思う何をしません。

sizeofは、コンパイル時で評価され、この場合にargv[1]がポインタであるので、(あなたは64ビットマシンにしていると仮定します)8を返します。

あなたは(実行時にのみ知ることができる)、文字列の長さをしたいので、あなたの代わりに使用する必要があります。

strlen(argv[1]) 

1からsizeofがで評価される場合があります。ランタイム。これはその1つではありません。

+0

私はそれを変更し、それは動作します、ありがとう! –

関連する問題