有名管道
博文
https://www.cnblogs.com/fangshenghui/archive/2004/01/13/4039805.html
编程步骤:
步骤 | 进程1 | 进程2 | 使用函数 |
---|---|---|---|
1 | 建立管道文件 | mfifo | |
2 | 打开管道 | 打开管道 | open |
3 | 读写数据 | 读写数据 | write/read |
4 | 关闭管道 | 关闭管道 | close |
5 | 删除管道 | 删除管道 | unlink |
使用实例
进程1:写管道
const char *fifo_name = "/tmp/my_fifo";
int pipe_fd = -1;
int data_fd = -1;
int res = 0;
const int open_mode = O_WRONLY;
int bytes_sent = 0;
char buffer[PIPE_BUF + 1];
int bytes_read = 0;
if(access(fifo_name, F_OK) == -1)
{
printf ("Create the fifo pipe.\n");
//建立管道
res = mkfifo(fifo_name, 0777);
if(res != 0)
{
fprintf(stderr, "Could not create fifo %s\n", fifo_name);
exit(EXIT_FAILURE);
}
}
printf("Process %d opening FIFO O_WRONLY\n", getpid());
//打开管道
pipe_fd = open(fifo_name, open_mode);
printf("Process %d result %d\n", getpid(), pipe_fd);
if(pipe_fd != -1)
{
bytes_read = 0;
data_fd = open("Data.txt", O_RDONLY);
if (data_fd == -1)
{
close(pipe_fd);
fprintf (stderr, "Open file[Data.txt] failed\n");
return -1;
}
bytes_read = read(data_fd, buffer, PIPE_BUF);
buffer[bytes_read] = '\0';
while(bytes_read > 0)
{
//写管道
res = write(pipe_fd, buffer, bytes_read);
if(res == -1)
{
fprintf(stderr, "Write error on pipe\n");
exit(EXIT_FAILURE);
}
bytes_sent += res;
bytes_read = read(data_fd, buffer, PIPE_BUF);
buffer[bytes_read] = '\0';
}
//关闭管道
close(pipe_fd);
close(data_fd);
}
进程2:读管道
const char *fifo_name = "/tmp/my_fifo";
int pipe_fd = -1;
int data_fd = -1;
int res = 0;
int open_mode = O_RDONLY;
char buffer[PIPE_BUF + 1];
int bytes_read = 0;
int bytes_write = 0;
memset(buffer, '\0', sizeof(buffer));
printf("Process %d opening FIFO O_RDONLY\n", getpid());
//打开管道
pipe_fd = open(fifo_name, open_mode);
data_fd = open("DataFormFIFO.txt", O_WRONLY|O_CREAT, 0644);
if (data_fd == -1)
{
fprintf(stderr, "Open file[DataFormFIFO.txt] failed\n");
close(pipe_fd);
return -1;
}
printf("Process %d result %d\n",getpid(), pipe_fd);
if(pipe_fd != -1)
{
do
{
//读管道
res = read(pipe_fd, buffer, PIPE_BUF);
bytes_write = write(data_fd, buffer, res);
bytes_read += res;
}while(res > 0);
//关闭管道
close(pipe_fd);
close(data_fd);
}