Pipe () between child and parent process

I am writing this code for pipe () between a child and a parent process. I need to make sure this is the correct code or not. By the way, he gives the answer that you can see!

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



int main(int argc, char *argv[]){
    pid_t pid;
    int fd[2];
    char buf[20];

pipe(fd);


switch(pid = fork()){

    case -1:
        perror("pipe");
        exit(1);

    case 0: 
        /*child process*/
        close(fd[1]);
        read(fd[0], buf, 20);
        printf("Child read message from parent: %s\n", buf);
        exit(1);
        break;

    default:
     /*parent process*/
        close(fd[0]);
        write(fd[1], "Hello from parent\n", 17);
        break;
    } 
    return 0;

}
+4
source share
1 answer

The operator switchbasically works fine, although you do not need a variable pid, since you are not doing anything with it.

The parent code is also basically normal, but the string is actually 18 bytes without the NUL terminator and 19 bytes with the NUL terminator. It is good practice to handle the newline and NUL characters in the child, so I would stick to 17 and remove the new line from the line.

. read. , , read . NUL . C "" , ( NUL '\0'). , , , NUL, NUL.

, :

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

int main( void )
{
    int fd[2];
    char buffer[20];

    if ( pipe(fd) < 0 ) {
        perror( "pipe" );
        exit( 1 );
    }

    switch( fork() ) {
        case -1:
            perror( "fork" );
            exit( 1 );

        case 0:
            /*child process*/
            close(fd[1]);
            ssize_t count = read( fd[0], buffer, sizeof(buffer)-1 );
            if ( count <= 0 ) {
                perror( "read" );
                exit( 1 );
            }
            buffer[count] = '\0';
            printf( "Child read message from parent: %s\n", buffer );
            exit(1);

        default:
            /*parent process*/
            close(fd[0]);
            char *message = "Hello from parent";
            size_t length = strlen( message );
            write( fd[1], message, length );
            break;
    }

    return 0;
}
+5

Source: https://habr.com/ru/post/1658969/


All Articles