FIFO

2018-12-13  本文已影响0人  之江狂徒

#include <stdio.h>

#include <stdlib.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <time.h>

#include <unistd.h>

#include <errno.h>

int main(int argc, char **argv)

{

int fd;

int len;

char buf[1024];

if(mkfifo("fifo1",0666) < 0 && errno != EEXIST)

perror("Create FIFO Failed");

if((fd = open("fifo1", O_RDONLY)) < 0) {

perror("Open FIFO Failed");

exit(1);

}

while((len = read(fd, buf, 1024)) > 0)

printf("Read message: %s\n", buf);

close(fd);

printf("finish read process\n");

return 0;

}


fifo_read.c

#include <stdio.h>

#include <stdlib.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <time.h>

#include <unistd.h>

int main(int argc, char **argv)

{

int fd;

int n, i;

char buf[1024];

time_t tp;

printf("I am %d process.\n", getpid());

if((fd = open("fifo1", O_WRONLY)) < 0) {

perror("Open FIFO Failed");

exit(1);

}

for(i=0; i<10; i++) {

time(&tp);

n = sprintf(buf, "Process %d's time is %s", getpid(), ctime(&tp));

printf("Send message: %s", buf);

if(write(fd, buf, n+1) < 0) {

perror("Write FIFO Failed");

close(fd);

exit(1);

}

sleep(1);

}

printf("finish write process\n");

close(fd);

return 0;

}


上一篇 下一篇

猜你喜欢

热点阅读