作业1:使用有名管道,完成两个进程的相互通信
1
#include <head.h>
int main(int argc, const char *argv[])
{
mkfifo("./1fifo1", 0664);
int wfd = -1;
if((wfd=open("./1fifo1", O_WRONLY)) == -1)
{
perror("wfd open error\n");
return -1;
}
pid_t pid = fork();
if(pid>0)
{
//父进程
char wbuf[128] = "";
while(1)
{
printf("1管道请输入>>>");
fgets(wbuf, sizeof(wbuf), stdin);
wbuf[strlen(wbuf)-1] = 0;
write(wfd, wbuf, sizeof(wbuf));
if(strcmp(wbuf, "quit") == 0)
{
break;
}
}
close(wfd);
wait(NULL);
}
else if(pid == 0)
{
//子进程
int rfd = -1;
if((rfd = open("./2fifo2",O_RDONLY)) == -1)
{
return -1;
}
printf("进入管道2读端\n");
char rbuf[128] = "";
while(1)
{
bzero(rbuf, sizeof(rbuf));
read(rfd, rbuf, sizeof(rbuf));
printf("2管道收入消息: %s\n", rbuf);
if(strcmp(rbuf, "quit") == 0)
{
break;
}
}
close(rfd);
exit(EXIT_SUCCESS);
}
else
{
perror("fork error\n");
return -1;
}
system("rm 1fifo1");
return 0;
}
2
#include <head.h>
int main(int argc, const char *argv[])
{
mkfifo("./2fifo2", 0664);
pid_t pid = fork();
if(pid>0)
{
//父进程
int wfd = -1;
if((wfd=open("./2fifo2", O_WRONLY)) == -1)
{
perror("wfd open error\n");
return -1;
}
char wbuf[128] = "";
while(1)
{
printf("2管道请输入>>>");
fgets(wbuf, sizeof(wbuf), stdin);
wbuf[strlen(wbuf)-1] = 0;
write(wfd, wbuf, sizeof(wbuf));
if(strcmp(wbuf, "quit") == 0)
{
break;
}
}
close(wfd);
wait(NULL);
}
else if(pid == 0)
{
//子进程
int rfd = -1;
if((rfd = open("./1fifo1",O_RDONLY)) == -1)
{
return -1;
}
printf("进入管道1读端\n");
char rbuf[128] = "";
while(1)
{
bzero(rbuf, sizeof(rbuf));
read(rfd, rbuf, sizeof(rbuf));
printf("1管道收入消息: %s\n", rbuf);
if(strcmp(rbuf, "quit") == 0)
{
break;
}
}
close(rfd);
exit(EXIT_SUCCESS);
}
else
{
perror("fork error\n");
return -1;
}
return 0;
}