2016-06-27 66 views
0

我正試圖在父子進程之間創建一個管道。 在這個管道中,子進程將寫入數據,父進程將讀取並打印它。 我不知道爲什麼,但如果我輸入一個大字符串的數據出錯了,對於帶有+ - 7個字的字符串,它仍然沒有問題。 我想這是關於緩衝區的大小,但無法修復它。創建父親和子進程之間的管道

#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在編譯時被評估,並且在這種情況下,將返回圖8(假設你是一個64位機器上),因爲argv[1]是一個指針。

因爲你想要的字符串(只能在運行時已知)的長度,應改用:

strlen(argv[1]) 

1 - 有哪裏sizeof在評估情況運行。這不是其中的一個。

+0

好吧,我改變了它,它的工作原理,謝謝! –