pipe usage in virtual tty
i am using a simple pipe programing for writing and reading the tty which made from inserting the program code from the linux device driver book version 3 of o'reilly. i inserted this 开发者_如何学运维via insmod
,and obtained the device named tinytty0
.
my question is can i use this device to read and write data via pipe? i tried once ,the data is writeng into driver but reading has not be done. i dont know what the reason. the code is given below
#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);
}
You must be misunderstanding what the tinytty
driver from the Linux Device Drivers
book does. From the book:
This sample tiny tty driver does not connect to any real hardware, so its write func- tion simply records in the kernel debug log what data was supposed to be written.
It is not some kind of loopback TTY driver, in fact, it sends a constant character ('t'
) every two seconds to whatever is reading from the device (see the function tiny_timer
).
Now, on to your piping issues. What I see from your code is that you have essentially created a pipe. Then, in your child process, you close the read end of the pipe, and discard the write end by replacing it with a file descriptor to your tiny tty
device (which is bad practice, as you have basically leaked an open file descriptor). Then, in your parent process, you close the write end of the pipe and discard the read end (still bad practice, ie. "leaking open file descriptors"). Finally, in the same parent process, you attempt to read from what you call the pipe
, which is not really a pipe anymore, since you've closed one end and replaced the other with a descriptor to the tiny tty
device. Moreover, the timer in the driver (that goes off every two seconds) probably hasn't gone off, which means there's nothing for you to read. I believe this explains your problem.
For anyone interested, the book being referred to here is available under the terms of the Creative Commons Attribution-ShareAlike 2.0 license from LWN.net, and the example drivers/code is available from O'Reilly.
精彩评论