管道的使用类似于创建一个文件,我们可以使用mkfifo()函数创建一个有名管道。
函数mkfifo()
所需头文件:#include<sys/types.h>
#include<sys/stat.h>
函数原型:int mkfifo(const char *pathname, mode_t mode)
函数参数:
pathname 要创建的有名管道的路径名与文件名
mode 创建的有名管道的文件权限码,通常用八进制数字表示
函数返回值:
成功:0
失败:-1
今天学了管道,就用管道模拟本地聊天室功能 ,我也承认代码写的的确渣,贴出来让大家指导一下,后续有时间再去完善,(结束回话逻辑不行),大家就当看着玩玩
小华
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#define MAX 256
int main(int argc, const char *argv[])
{
int fd,fd2;
char buf[MAX]={0};
char str[MAX]={0};
if(argc<3)
{
printf("too few arguments\n");
exit(0);
}
if((fd=open(argv[1],O_WRONLY))<0)
{
perror("open file fail");
exit(0);
}
if((fd2=open(argv[2],O_RDONLY))<0)
{
perror("open file fail");
exit(0);
}
int n;
do
{
printf("please input string:");
scanf("%[^\n]",buf);
getchar();
write(fd,buf,strlen(buf));
n=strncmp(buf,"b",1);
printf("小明:");
read(fd2,str,MAX);
printf("%s\n",str);
// bzero(str,MAX);
}while(n!=0);
close(fd);
close(fd2);
return 0;
}
小明
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#define MAX 256
int main(int argc, const char *argv[])
{
int fd,fd2;
char buf[MAX]={0};
char str[MAX]={0};
if(argc<3)
{
printf("too few arguments\n");
exit(0);
}
if((fd=open(argv[1],O_RDONLY))<0)
{
perror("open file fail");
exit(0);
}
if((fd2=open(argv[2],O_WRONLY))<0)
{
perror("open file fail");
exit(0);
}
int n;
do
{
printf("小华: ");
read(fd,buf,MAX);
printf("%s\n",buf);
bzero(buf,MAX);
printf("please input string:");
scanf("%[^\n]",str);
getchar();
write(fd2,str,strlen(str));
n=strncmp(str,"b",1);
}while(n=!0);
close(fd);
close(fd2);
return 0;
}