简体   繁体   中英

Using Pipes in C

I wrote the following code to help me understand how pipes work in C.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

struct sum_ {
    int a;
    int b;
};

int main (void) {
    int pipe1[2];
    int pid;
    struct sum_ sum;

    if ( (pipe(pipe1) != 0)){
        printf("pipe(): %d %s\n", errno, strerror(errno));
        exit(1);
    }

    pid = fork();
    if (pid == -1) {
        printf("fork(): %d %s\n", errno, strerror(errno));
        exit(1);
    }
    else if (pid == 0) { // Child
        close(pipe1[0]);

        sleep(5);
        sum.a = read(pipe1[0], &sum.a, sizeof(sum.a));

        printf("Your number was: %d", sum.a);
    }
    else { // Father
        close(pipe1[1]);

        printf("\nWrite a number: \n");
        char a[4];
        sum.a = atoi(fgets(a, 4, stdin));

        write(pipe1[1], &sum.a, sizeof(sum.a));
    }

    return 0;
}

The code has a father and a son process. It is quite simple, the father uses a pipe to send a number to the son and the son displays the number for the user. I always get -1 as result. What have I done wrong?

 close(pipe1[0]);

 sleep(5);
 sum.a = read(pipe1[0], &sum.a, sizeof(sum.a));

You close the file descriptor pipe1[0] , then read from it (and so get -1 returned). You make the equivalent error in the father, too. I think you mean to close pipep1[0] here and pipe1[1] in the father

Also, when you fix that, lthough you're reading into sum.a by passing the address, you're also setting it from the return value, which will overwrite what you read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM