notes/snippet/cpp/ipc/fifo_write.c

40 lines
800 B
C

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<time.h>
#include <unistd.h>
#define MAX_BUFF 1024
#define FIFO_FILE "fifo_file"
int main(int argc, char **argv) {
int fd;
int n, i;
char buff[MAX_BUFF];
time_t timestamp;
printf("I'm process %d\n", getpid());
if ((fd = open(FIFO_FILE, O_WRONLY)) < 0) {
printf("Open %s fails\n", FIFO_FILE);
exit(1);
}
for (i = 0; i < 10; i++) {
time(&timestamp);
n = sprintf(buff, "Process %d at %s", getpid(), ctime(&timestamp));
printf("Send msg: %s\n", buff);
if (write(fd, buff, n+1) < 0) {
perror("Write fd fails\n");
close(fd);
exit(1);
}
sleep(1);
}
close(fd);
return 0;
}