天天看點

Linux下的有名管道---使用兩個管道實作兩個程序之間的通信(手機模式)

環境:Vmware Workstation;CentOS-6.4-x86_64

說明:

對講機模式:一個程序輸入完成一句話,必須等待第二個程序輸入完成一句話之後才能再次輸入。

步驟:

1、建立兩個管道:

[negivup@negivup mycode]$ mkfifo fifo1
[negivup@negivup mycode]$ mkfifo fifo2
[negivup@negivup mycode]$ ls
fifo1  fifo2      

2、編寫makefile檔案:

.SUFFIXES:.c .o
 
CC=gcc
 
SRCS1=readfifo.c
OBJS1=$(SRCS1:.c=.o)
EXEC1=readfifo
 
SRCS2=writefifo.c
OBJS2=$(SRCS2:.c=.o)
EXEC2=writefifo
 
start: $(OBJS1) $(OBJS2)
  $(CC) -o $(EXEC1) $(OBJS1)
  $(CC) -o $(EXEC2) $(OBJS2)
  @echo "--------------------------OK------------------------"
 
.c.o:
  $(CC) -Wall -o $@ -c $<
 
clean:
  rm -rf $(OBJS1) $(EXEC1)
  rm -rf $(OBJS2) $(EXEC2)      

3、編寫讀取管道的源檔案readfifo.c:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
 
int main(void)
{
  pid_t pid = fork(); //建立了兩個程序,父子關系
  if (pid > 0) //在主程序裡面
  {
    int fd1 = open("fifo1", O_WRONLY);
    if (fd1 == -1)
    {
      printf("open fifo1 error, %s\n", strerror(errno));
      return -1;
    }
    char buf[1024];
    while (1)
    {
      memset(buf, 0, sizeof(buf));
      read(STDIN_FILENO, buf, sizeof(buf));
      write(fd1, buf, strlen(buf));
    }
    close(fd1);
  } else
  {
    int fd1 = open("fifo2", O_RDONLY);
    if (fd1 == -1)
    {
      printf("open fifo2 error, %s\n", strerror(errno));
      return -1;
    }
    char buf[1024];
    while (1)
    {
      memset(buf, 0, sizeof(buf));
      read(fd1, buf, sizeof(buf));
      printf("%s", buf);
    }
    close(fd1);
  }
  return 0;
}      

4、編寫寫入管道的源檔案writefifo.c:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
 
int main(void)
{
  pid_t pid = fork(); //建立了兩個程序,父子關系
  if (pid > 0) //在主程序裡面
  {
    int fd1 = open("fifo2", O_WRONLY);
    if (fd1 == -1)
    {
      printf("open fifo2 error, %s\n", strerror(errno));
      return -1;
    }
    char buf[1024];
    while (1)
    {
      memset(buf, 0, sizeof(buf));
      read(STDIN_FILENO, buf, sizeof(buf));
      write(fd1, buf, strlen(buf));
    }
    close(fd1);
  } else
  {
    int fd1 = open("fifo1", O_RDONLY);
    if (fd1 == -1)
    {
      printf("open fifo1 error, %s\n", strerror(errno));
      return -1;
    }
 
    char buf[1024];
    while (1)
    {
      memset(buf, 0, sizeof(buf));
      read(fd1, buf, sizeof(buf));
      printf("%s", buf);
    }
    close(fd1);
  }
  return 0;
}      

5、編譯并執行readfifo:

[negivup@negivup mycode]$ make
gcc -Wall -o readfifo.o -c readfifo.c
gcc -Wall -o writefifo.o -c writefifo.c
gcc -o readfifo readfifo.o
gcc -o writefifo writefifo.o
--------------------------OK------------------------
[negivup@negivup mycode]$ readfifo      

6、打開一個新的終端,執行writefifo:

[negivup@negivup mycode]$ writefifo 
safd      

繼續閱讀