2016-06-27 5 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

хорошо, я изменил его, и он работает, спасибо! –

Смежные вопросы