Home > Back-end >  When passing processed in the child result to parent, printf() outputs the proper value, but write()
When passing processed in the child result to parent, printf() outputs the proper value, but write()

Time:10-12

It's a simple program that passes a value from parent to child which processes it and then returns it back to parent, which then is supposed to output the processed value to the terminal. While printf() does the job, write() doesn't output anything. If there is a way to output the result using write(), how should it be done?

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

    if (id == -1){ perror("fork error"); return -1; }
    else if (id == 0){ // child
        int x;
        read(fd[0], &x, sizeof(int));

        // ...
        // process x
        // ...
        
        int res = x;
        write(fd[1], &res, sizeof(int));

        close(fd[0]);
        close(fd[1]);
    }
    else{ // parent
        int x = 10;
        write(fd[1], &x, sizeof(int));

        int res;
        read(fd[0], &res, sizeof(int));

        //printf() works whilst write() doesn't
        write(0, &res, sizeof(int));
        //printf("%d\n", res);

        close(fd[0]);
        close(fd[1]);
    }
}

CodePudding user response:

The write function doesn't know anything about text, all it will do are write the raw bytes.

So write(0, &res, sizeof(int)) will write the raw binary data of res, which very likely will not be equal to any valid characters.

If you want to use write, use e.g. snprintf to "print" to a buffer, and then write that buffer:

char buffer[30];
snprintf(buffer, sizeof buffer, "%d", res);

write(STDOUT_FILENO, buffer, strlen(buffer));
  • Related