子进程和父进程之间的pipe()

时间:2016-10-26 17:19:45

标签: c operating-system

我在child和parent进程之间为pipe()编写了这段代码。我需要确保这是否是正确的代码。顺便说一句,它给出了想要看到的答案!

#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;

}

1 个答案:

答案 0 :(得分:5)

switch语句基本上没问题,但你不需要pid变量,因为你没有对它做任何事情。

父代码也很好,但是字符串实际上是没有NUL终结符的18个字节,而是带有NUL终结符的19个字节。在孩子中处理换行符和NUL终止符是一个好习惯,所以我会坚持使用17并从字符串中删除换行符。

子代码错误。您需要一个变量来存储read的返回值。您需要检查返回值以确保read成功。并且您需要在字符串中添加NUL终止符。在C编程语言中,“string”是一个以零字节结尾的字符数组(称为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;
}