1

我正在使用一个简单的管道编程来编写和读取 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);
}
4

1 回答 1

1

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

这个示例微型 tty 驱动程序不连接到任何实际硬件,因此它的写入功能只是在内核调试日志中记录应该写入的数据。

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

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


对于任何感兴趣的人,这里提到的书都可以根据LWN.net的 Creative Commons Attribution-ShareAlike 2.0 许可的条款获得,示例驱动程序/代码可以从O'Reilly获得。

于 2011-07-19T03:18:12.793 回答