这是生产者。
// speak.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char s[300];
int num, fd;
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for readers...
");
fd = open(FIFO_NAME, O_WRONLY);
printf("got a reader--type some stuff
");
while (gets(s), !feof(stdin)) {
if ((num = write(fd, s, strlen(s))) == -1)
perror("write");
else
printf("speak: wrote %d bytes
", num);
}
return 0;
}
这是消费者。
//tick.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char s[300];
int num, fd;
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for writers...
");
fd = open(FIFO_NAME, O_RDONLY);
printf("got a writer
");
do {
if ((num = read(fd, s, 300)) == -1)
perror("read");
else {
s[num] = ;
printf("tick: read %d bytes: "%s"
", num, s);
}
} while (num > 0);
return 0;
}
当我管理这些产品时,生产者的产出就是:
waiting for readers...
消费者产出
waiting for writers...