我尝试在linux上用c语言学习管道

时间:2012-10-28 17:10:45

标签: c linux pipeline

我尝试在linux上用c语言学习管道。 我写跟随程序。 这个程序有错误吗?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>


int main (void)
{
    int fd[2], nbytes;
    pid_t childpid;
    char string[]= "Hello, World!\n";
    char readbuffer[80];


    pipe(fd);

    if((childpid = fork()) == -1)
    {
        perror("fork");
        exit(0);    
    } 

    if(childpid == 0)
    {
        // child process closes up input side of pipe.
        close(fd[0]);

        // send "string" through the output side of pipe.
        write(fd[1], string, strlen(string));
        exit(0);
    }

    else
    {
        // parent process closes up output side of pipe.
        close(fd[0]);

        // Read in a string from pipe.
        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        printf("Received string = %s\n", readbuffer);
    }

    return 0;
}

有什么问题吗?

1 个答案:

答案 0 :(得分:1)

这两段代码中的一段不正确,只是基于评论:

if (childpid == 0)
{
    // child process closes up input side of pipe.
    close(fd[0]);

else
{
    // parent process closes up output side of pipe.
    close(fd[0]);

您实际上需要在父级(写作端)中关闭fd[1]。令人惊讶的是,您的read调用是正确的,但是正在从您刚刚关闭的文件描述符中读取。

请注意,您应该只打印您阅读的内容(仅当您成功阅读内容时):

if (nbytes > 0)
    printf("Received string: <<%.*s>>\n", nbytes, readbuffer);
else if (nbytes == 0)
    printf("Received no data\n");
else
    printf("Received error (%d: %s)\n", errno, strerror(errno));

(请注意,您需要<errno.h><string.h>才能正确编译最后一行。)

<<>>标记很简单,因此您可以看到尾随空白等。如果您愿意,可以省略它们。