Interprocess communication sending structure via pipe

I believe you are expecting that the if block runs in the child process and else block is running in parent process and the fork is called before the code segment. In that case the p in two process are different for two process and they are not connected.

Your read call if throwing a error. Can you check the return value at of the read system call?

The modified code snipped should looks like

    if (pipe(p) < 0)
        exit(1);
    if (fork() < 0)
        exit(1);
    if (pid == 0){
        //I get the time 
        gettimeofday(&current,NULL);
        //I write it in the pipe, if I print the time here i get the result I want
        if (write(p[1], &current, sizeof(current)) < 0) {
            perror("write");
            exit(1);
        }
        close(p[1]);
        //then I execute the command
    }else{
        if (waitpid(pid, &status, 0) > 0){
            close(p[1]);
            struct timeval inicio;
            //Here is the problem I think, once I tried to read it I get a random number
            if (read(p[0], &inicio, sizeof(inicio)) < 0) {
                perror("read");
                exit(1);
            }
            printf(": %ld,%ld\n", inicio.tv_sec,inicio.tv_usec); 
            
        }else{
            printf("waitpid() failed\n");
        }
        exit(0);
    }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top