【问题标题】:pipe usage in virtual tty虚拟 tty 中的管道使用情况
【发布时间】:2011-07-12 08:42:22
【问题描述】:

我正在使用一个简单的管道编程来编写和读取 tty,它是通过插入来自 o'reilly 的 linux 设备驱动程序手册第 3 版的程序代码而制成的。我通过insmod 插入了这个,并获得了名为tinytty0 的设备。

我的问题是我可以使用这个设备通过管道读取和写入数据吗?我试过一次,数据正在写入驱动程序,但读取尚未完成。我不知道是什么原因。代码如下

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<fcntl.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(1);
        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);
            fd[1]=open("/dev/ttytiny0",O_WRONLY);   
        if(fd[1]<0)
        {
            printf("the device is not opened\n");
            exit(-1);
        }   
                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
                exit(0);
        }
        else
        {

                /* Parent process closes up output side of pipe */
                close(fd[1]);
        fd[0]=open("/dev/ttytiny0",O_RDONLY);
        if(fd[0]<0)
        {
            printf("the device is not opened\n");
            exit(-1);
        }
                /* Read in a string from the pipe */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received string: %s", readbuffer);
        }

        return(0);
}

【问题讨论】:

  • read的返回值是多少(nbytes的值)?

标签: c pipe virtual tty


【解决方案1】:

您一定误解了Linux Device Drivers 书中的tinytty 驱动程序的作用。从书中:

这个示例微型 tty 驱动程序不连接到任何真实的硬件,所以它的写函数 仅在内核调试日志中记录应该写入的数据。

它不是某种环回 TTY 驱动程序,事实上,它每两秒向从设备读取的任何内容发送一个常量字符 ('t')(参见函数 tiny_timer)。

现在,谈谈您的管道问题。我从您的代码中看到的是您实际上已经创建了一个管道。然后,在您的子进程中,您关闭管道的读取端,并通过将其替换为 tiny tty 设备的文件描述符来丢弃写入端(这是不好的做法,因为您基本上泄露了一个打开的文件描述符) .然后,在您的父进程中,您关闭管道的写入端并丢弃读取端(仍然是不好的做法,即“泄漏打开的文件描述符”)。最后,在同一个父进程中,您尝试从您称为pipe 的内容中读取,这不再是真正的管道,因为您已经关闭了一端并将另一端替换为tiny tty 设备的描述符。此外,驱动程序中的计时器(每两秒关闭一次)可能还没有关闭,这意味着您没有任何内容可供阅读。我相信这可以解释您的问题。


对于任何感兴趣的人,此处引用的书可根据知识共享署名-相同方式共享 2.0 许可条款从LWN.net 获得,示例驱动程序/代码可从O'Reilly 获得。

【讨论】:

    猜你喜欢
    • 2014-08-06
    • 2014-06-29
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多