#include #include #include #include #include #include #include #include #include #include "common.h" void Usage(char *program) { fprintf(stderr, "Usage: %s \n", program); exit(1); } void CheckFiles(char *fifo, char *data) { // make sure they are the right types of files if (IsFifo(fifo) == 0) { fprintf(stderr, "%s is not a FIFO!\n", fifo); exit(1); } if (IsRegular(data) == 0) { fprintf(stderr, "%s is not a regular file\n", fifo); exit(1); } } int IsValid(char *str) { int len = strlen(str); if (len == 0) return 0; // check first digit special: minus sign or digit if ((str[0] != '-') && (isdigit(str[0]) == 0)) return 0; // check rest: just digits for (int i = 1; i < len; i++) { if (isdigit(str[i]) == 0) { return 0; } } return 1; } void MsgSend(int pipe, msg_t *m) { // send on pipe if (write(pipe, m, sizeof(msg_t)) != sizeof(msg_t)) { perror("write"); // not much to do about this other than continue } } int main(int argc, char *argv[]) { // takes two arguments: fifofile and datafile if (argc != 3) { Usage(argv[0]); } char *fifoFile = argv[1]; char *dataFile = argv[2]; // first, check that fifo is a FIFO, and data is a data file, then open both CheckFiles(fifoFile, dataFile); int pipe = open(fifoFile, O_WRONLY); if (pipe < 0) { perror("open"); Usage(argv[0]); } FILE *fp = fopen(dataFile, "r"); if (fp == NULL) { perror("fopen"); Usage(argv[0]); } // // main loop // msg_t m; char line[MAX_LINE]; while (fgets(line, MAX_LINE, fp) != NULL) { // printf("%s", line); // check for comments if (line[0] == '#') { continue; } // parse line: use strtok() to split up line into little bits char *p = strtok(line, WHITESPACE); while (p != NULL) { // check if token is a valid integer if (IsValid(p)) { // form message and send it m.type = DATA; m.data = atoi(p); MsgSend(pipe, &m); } // get next token here p = strtok(NULL, WHITESPACE); } } // all done, send the END message m.type = END; // doesn't matter what 'data' field is set to MsgSend(pipe, &m); // close up shop and be done with it close(pipe); fclose(fp); return 0; }