UNIX环境高级编程学习之第十五章进程间通信 - 通过有名管道(命名管道)实现进程间通信
[code lang="cpp"]/* User:Lixiujie
* Date:20100820
* Desc:通过有名管道实现进程间通信
* File:writeFifo.c
* gcc writeFifo.c -o writeFifo
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
int main(void){
int fd = open("fifo", O_WRONLY);
if (fd < 0){
mode_t mode = 0666;
if (mkfifo("fifo", mode) < 0){
perror("mkfifo failed!");
exit(1);
}
fd = open("fifo", O_WRONLY);
if (fd < 0){
perror("open failed!");
exit(1);
}
}
int i;
time_t t;
for (i = 0;i < 10;i++){
char szBuf[512] = { 0x00 };
time(&t);
sprintf(szBuf, "writeFifo %d Send:%s", getpid(), ctime(&t));
if (write(fd, szBuf, strlen(szBuf) + 1) < 0){
perror("write failed!");
exit(1);
}
sleep(3);
}
close(fd);
return 0;
}
[/code]
文章评论