Omri Ziner
Omri Ziner

Reputation: 83

creating pipe between father and child process

I'm trying to create a pipe between father and child process. in this pipe, the child process will write data and the father will read and print it. I don't know why but if I enter a big string the data got wrong, for strings with +- 7 words it still do fine. I guess it is about the size of the buffer but can't fix it.

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

Upvotes: 0

Views: 858

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137557

sizeof(argv[1])

This does not do what you think it does.

sizeof is evaluated at compile-time1, and in this case will return 8 (assuming you're on a 64-bit machine), because argv[1] is a pointer.

Because you want the length of the string (which can only be known at run-time), you should instead use:

strlen(argv[1])

1 - There are cases where sizeof is evaluated at run-time. This is not one of them.

Upvotes: 1

Related Questions