Question

I have a code snippet like this (test code, so don't mind the style too much):

int main() {
    int fd[2];
    pipe(fd);
    int id = fork();

    if (id > 0) {
        char *line = "apple";
        close(fd[0]);
        for (;;) {
            int written;
            if (written = write(fd[1], line, 7) == -1) {
                break;
            }
            printf("written %d\n", written);
            sleep(1);
        }
        close(fd[1]);
    }
    else {
        char line[10];
        close(fd[1]);
        int raed;
        while (raed = read(fd[0], line, 10) > 0) {
            printf(line);
        }
        printf("read %d\n", raed);
        close(fd[0]);
    }
    return 0;
}

It keeps printing "written 0". However, if I comment out sleep(1), it still always prints "written 0" but there will be "apple" printed. I don't know what is going on. Why can't I keep the sleep(1) and let it print every 1 second? And why does it write 0 rather than 6?

Was it helpful?

Solution

if (written = write(fd[1], line, 7) == -1)

there is a mistake use if ((written = write(fd[1], line, 7)) == -1)

most of the time coders forget this often...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top