#include
int pipe(int fd[2]);
功能: 创建匿名管道
参数:fd:⽂文件描述符数组,其中fd[0]表⽰示读端, fd[1]表⽰示写端
返回值: 成功返回0,失败返回错误代码
#include
#include
#include
#include
int main()
{
int fds[2];
char buf[100];
int len;
if(pipe(fds) == -1)
perror("make pipe"),exit(1);
//读取数据
while(fgets(buf,100,stdin))
{
len = strlen(buf);
//写入管道
if(write(fds[1],buf,len) != len)
{
perror("write to pipe");
break;
}
memset(buf,0x00,sizeof(buf));
//从管道中读取
if((len=read(fds[0],buf,100)) == -1)
{
perror("read from pipe");
break;
}
//显示管道中内容
if(write(1,buf,len) != len)
{
perror("write to stdout");
break;
}
}
}
由此可见,管道的使用和文件一样,正如Linux中的一切皆文件思想。
#include
#include
#include
#include
#include
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int pipefd[2];
char buf[10] = {0};
if(pipe(pipefd) == -1)//创建pipe管道
ERR_EXIT("pipe error");
pid_t pid;
pid = fork();//创建子进程
if(pid == -1)
ERR_EXIT("fork error");
if(pid == 0)
{
close(pipefd[0]);//关闭子进程读操作
write(pipefd[1],"hello",5);//写入字符
printf("pid = %d,ppid = %d\n",getpid(),getppid());//确认为子进程
close(pipefd[1]);
exit(EXIT_SUCCESS);//退出子进程
}
printf("pid = %d,ppid = %d\n",getppid(),getpid());//确认为父进程
close(pipefd[1]);//关闭写操作
read(pipefd[0],buf,10);//读10个字符
printf("buf = %s\n",buf);//显示读的字符
return 0;
}
进行不相关进程的进程间通信。
命名管道可以从命令行上创建:
$ mkfilo filename
从程序创建:
int mkfile(const char *filename,mode_t mode);
创建命名管道:
int main(int argc, char &argv[])
{
mkfifo("管道名(一个FIFO文件)", 0644);
return 0;
}
#include
#include
#include
#include
#include
#include
#include
#include
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int infd;
int outfd;
char buf[1024];
int n;
mkfifo("tp.c", 0644);//创建命名管道文件
infd = open("1.c", O_RDONLY);
if(infd == -1)
ERR_EXIT("open");
outfd = open("tp.c", O_WRONLY);
if(outfd == -1)
ERR_EXIT("open");
while((n = read(infd, buf, 1024)) > 0)//读取文件内容到buf上
{
write(outfd, buf, n);//变量内容写到管道文件中
}
close(infd);//关闭读操作
close(outfd);//关闭写操作
return 0;
}
#include
#include
#include
#include
#include
#include
#include
#include
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int infd;
int outfd;
int n;
char buf[1024];
outfd = open("1.c.bak",O_WRONLY | O_CREAT | O_TRUNC, 0644);
if(outfd == -1)
ERR_EXIT("open");
infd = open("tp.c",O_RDONLY);
if(outfd == -1)
ERR_EXIT("open");
while((n = read(infd,buf,1024)) > 0)
{
write(outfd,buf,n);
}
close(infd);
close(outfd);
unlink("tp.c");
return 0;
}