标签:
1 /*一个应用命名管道进行通信的实例*/
写端程序
2 #include<stdio.h> 3 #include<unistd.h> 4 #include<stdlib.h> 5 #include<sys/stat.h> 6 #include<sys/types.h> 7 #include<errno.h> 8 #include<sys/time.h> 9 #include<time.h> 10 #include<fcntl.h> 11 #include<limits.h> 12 #define BUFES PIPE_BUF 13 14 int main() 15 { 16 int fd; 17 int n,i; 18 char buf[BUFES]; 19 20 printf("I am process %d\n",getpid()); 21 if((fd=open("fifo1",O_WRONLY))<0) 22 { 23 printf("Open fifo failed!\n"); 24 exit(1); 25 } 26 27 struct timeval tp; 28 struct tm *tm; 29 30 for(i=0;i<10;i++) 31 { 32 gettimeofday(&tp,NULL); 33 tm=localtime(&tp.tv_sec); 34 n=sprintf(buf,"write_fifo %d seconds %d-%d-%d %d:%d:%d",getpid(),tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec); 35 printf("Send msg:%s\n",buf); 36 if(write(fd,buf,n+1)<0) 37 { 38 printf("Write failed!\n"); 39 close(fd); 40 exit(1); 41 } 42 sleep(3); 43 } 44 close(fd); 45 return 0; 46 }
读端程序
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<stdlib.h> 4 #include<sys/stat.h> 5 #include<sys/types.h> 6 #include<errno.h> 7 #include<fcntl.h> 8 #include<limits.h> 9 #define BUFES PIPE_BUF 10 11 int main() 12 { 13 int fd; 14 int i; 15 char buf[BUFES]; 16 time_t tp; 17 printf("I am process %d\n",getpid()); 18 if((fd=open("fifo1",O_RDONLY))<0) 19 { 20 printf("Open fifo failed!\n"); 21 exit(1); 22 } 23 24 while(read(fd,buf,BUFES)>0) 25 printf("Read_info read:%s\n",buf); 26 close(fd); 27 return 0; 28 }
程序编译(该程序需要在两个shell中运行)
1 gcc -o write_fifo.c 2 gcc -o read_fifo.c 3 mkfifo -m 666 fifo1 4 ./write_fifo //在shell 1中 5 ./read_fifo //在shell 2中
程序执行结果:
1 shell1中 2 I am process 10289 3 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:17 4 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:21 5 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:24 6 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:27 7 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:30 8 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:33 9 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:36 10 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:39 11 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:42 12 Send msg:write_fifo 10289 seconds 2016-2-5 18:44:45 13 14 15 shell2中 16 I am process 10288 17 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:17 18 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:21 19 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:24 20 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:27 21 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:30 22 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:33 23 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:36 24 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:39 25 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:42 26 Read_info read:write_fifo 10289 seconds 2016-2-5 18:44:45
并且我们看到如果先打开shell2的时候,其一直在等待shell1发送数据
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5183504.html