Linux进程间通信IPC学习笔记之管道

时间:2023-03-09 00:09:46
Linux进程间通信IPC学习笔记之管道

基础知识:

管道是最初的Unix IPC形式,可追溯到1973年的Unix第3版。使用其应注意两点:

1)没有名字;

2)用于共同祖先间的进程通信;

3)读写操作用read和write函数

#include <unistd.h>
int pipe(int
fildes[2]);

返回:成功返回1,否则返回-1.创建成功的两个文件描述符:f[0]和f[1],前者用来打开读,后者用来打开写。 #include <unistd.h>
ssize_t read(int fildes, void *buf, size_t nbyte);
ssize_t write(int fildes, const void *buf, size_t nbyte);

测试代码:

代码1

 #include<stdio.h>
#include<unistd.h> int main()
{
int n,fd[]; // 这里的fd是文件描述符的数组,用于创建管道做准备的
pid_t pid;
char line[];
if(pipe(fd)<) // 创建管道
printf("pipe create error/n"); if((pid=fork())<) //利用fork()创建新进程
printf("fork error/n");
else if(pid>)
{ //这里是父进程,先关闭管道的读出端,然后在管道的写端写入“hello world"
close(fd[]);
write(fd[],"hello word/n",);
}
else
{ //这里是子进程,先关闭管道的写入端,然后在管道的读出端读出数据
close(fd[]);
n= read(fd[],line,);
write(STDOUT_FILENO,line,n);
}
exit();
}

代码2

 #include <unistd.h>
#include <stdio.h> void client (int, int ) , server (int , int) ;
int main(int argc, char **argv)
{
int pipe1[] ,pipe2[];
pid_t childpid; pipe(pipe1);/* create two pipes */
pipe(pipe2); if ( (childpid = fork () ) == )
{ /* child */
close (pipe1[]) ;
close (pipe2[]) ;
server (pipe1[],pipe2[]) ;
exit () ;
}
/* parent */
close (pipe1[]) ;
close (pipe2[]) ;
client (pipe2[], pipe1[]) ; waitpid(childpid, NULL, ); /* wait for child to terminate */
exit() ; } void client(int readfd, int writefd)
{
size_t len;
ssize_t n;
char buff[MAXLINEI; /* read pathname */
fgets (buff, MAXLINE, stdin) ;
len = strlen(buf f) ; /* £gets() guarantees null byte at end */
if (buff [len - ] == '\n' )
len--; /* delete newline from £gets() */ /* write pathname to IPC channel */
write(writefd, buff, len); /* read from IPC, write to standard output */
while ( (n = Read(readfd, buff, MAXLINE)) > )
write(STD0UT_FILENO, buff, n):
}
void server(int readfd, int writefd)
{
int fd;
ssize_t n;
char buff [MAXLINE + ]; /* read pathname from IPC channel */
if ( (n = Read(readfd, buff, MAXLINE) ) == )
err-quit("end-of-file while reading pathname"):
buff[n] = '\0'; /* null terminate pathname */ if ( (fd = open(buff, O_RDONLY)) < )
{
/* error: must tell client */
snprintf(buff + n, sizeof(buff) - n, ": can't open, %s\",strerror(errn0));
n = strlen(buf f) ;
write(writefd, buff, n) ;
}
else
{
/* open succeeded: copy file to IPC channel */
while ( (n = Read(fd, buff, MAXLINE)) > )
write(writefd, buff, n);
close ( fd) ;
} }

Linux进程间通信IPC学习笔记之管道

参考资料

win32下的多线程命名管道通信的设计

linux管道

pipe fifo简介

Linux进程线程学习笔记:进程间通信之管道