管道文件
#include <myhead.h>
int main(int argc, const char *argv[])
{
//#include <sys/types.h>
// #include <sys/stat.h>
// int mkfifo(const char *pathname, mode_t mode);
//作用:创建一个有名管道
//参数1:创建管道文件的路径
//参数2:创建时的权限,0664
//返回值:成功返回0,失败返回-1并置位错误码。
//
//作业1:有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道.
int ABC = mkfifo("./ABC.1",0664);
if(ABC == -1)
{
perror("mkfifo");
return -1;
}
int CBA = mkfifo("./ABC.2",0664);
if(CBA == -1)
{
perror("mkfifo");
return -1;
}
return 0;
}
第一个程序
#include <myhead.h>
int main(int argc, const char *argv[])
{
//作业1:有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道.
pid_t pid;
pid = fork();
if (pid >0)
{
int ABC = open("./ABC.1",O_WRONLY);
if(ABC == -1)
{
perror("open");
return -1;
}
int len;
char buff[2048];
while(1)
{
//len = read(0,buff,sizeof(buff)-1);
// buff[len]='\0';
if(fgets(buff,sizeof(buff),stdin) == NULL)
{
perror("fgets");
break;
}
len = strlen(buff);
if (len > 0 && buff[len-1] == '\n')
{
buff[len-1] = '\0';
len--;
}
write(ABC,buff,len);
//char aaa[10]="stop";
if(strcmp(buff,"stop")==0)
{
break;
}
} close(ABC);
}
else if(pid == 0)//子进程
{
int ABC = open("./ABC.2",O_RDONLY);
if(ABC == -1)
{
perror("open");
return -1;
}
int len;
char buff[2048];
while(1)
{
len = read(ABC,buff,sizeof(buff)-1);
write(1,buff,len);
if (len <= 0)
{
if (len == 0)
{
printf("子进程: 管道已关闭\n");
}
else
{
perror("read from pipe2");
}
break;
}
buff[len]='\0';
if(strcmp(buff,"stop")==0)
{
break;
}
}
close(ABC);
exit(EXIT_SUCCESS);
}
else
{
perror("fork");
return -1;
}
return 0;
}
第二个文件
#include <myhead.h>
int main(int argc, const char *argv[])
{
//作业1:有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道.
pid_t pid;
pid = fork();
if (pid >0)
{
int ABC = open("./ABC.2",O_WRONLY);
if(ABC == -1)
{
perror("open");
return -1;
}
int len;
char buff[2048];
while(1)
{
//len = read(0,buff,sizeof(buff)-1);
// buff[len]='\0';
if(fgets(buff,sizeof(buff),stdin) == NULL)
{
perror("fgets");
break;
}
len = strlen(buff);
if (len > 0 && buff[len-1] == '\n')
{
buff[len-1] = '\0';
len--;
}
write(ABC,buff,len);
//char aaa[10]="stop";
if(strcmp(buff,"stop")==0)
{
break;
}
} close(ABC);
}
else if(pid == 0)//子进程
{
int ABC = open("./ABC.1",O_RDONLY);
if(ABC == -1)
{
perror("open");
return -1;
}
int len;
char buff[2048];
while(1)
{
len = read(ABC,buff,sizeof(buff)-1);
write(1,buff,len);
if (len <= 0)
{
if (len == 0)
{
printf("子进程: 管道已关闭\n");
}
else
{
perror("read from pipe2");
}
break;
}
buff[len]='\0';
if(strcmp(buff,"stop")==0)
{
break;
}
}
close(ABC);
exit(EXIT_SUCCESS);
}
else
{
perror("fork");
return -1;
}
return 0;
}