Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- A server that receives messages from a client and stores them in a file along
- with the current date and the identifiers
- **/
- #include "msg.h"
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/neutrino.h>
- #include <time.h>
- int main(int argc, char *argv[]) {
- //The node descriptor, process id, and connection id
- int nd = 0;
- int pid = getpid();
- int chid;
- //Where the message wil be stored
- MESSAGE msg;
- //File name for the PID file and the message file
- int rcvid;
- char *pidFileName;
- FILE *pidHandle;
- FILE *msgLogHandle;
- //To get the current time
- time_t currentCtime;
- char currentDate[26];
- //Name of the log file entered
- char *msgLogFile = argv[1];
- //Allocate memory and append .pid to the file
- pidFileName = malloc(strlen(argv[0]) + 5);
- strcpy(pidFileName, argv[0]);
- strcat(pidFileName, ".pid");
- //Open the file
- pidHandle = fopen(pidFileName, "w");
- //Check if channel was created
- if ((chid = ChannelCreate(0)) == -1) {
- perror("Logger couldn't create a channel");
- exit(EXIT_FAILURE);
- }
- //Place the identifier contents into the pid file
- if (fprintf(pidHandle, "%d %d %d", nd, pid, chid) < 0) {
- perror("Logger failed to write its pid file \n");
- exit(EXIT_FAILURE);
- }
- fclose(pidHandle);
- //Open the message log
- msgLogHandle = fopen(msgLogFile, "w");
- for(;;) {
- // Block and wait for a request from a client
- rcvid = MsgReceive (chid, &msg, sizeof(msg), NULL);
- switch (msg.m_hdr) {
- case MSG_DATA:
- //Message successfully received, store the data into the file
- MsgReply(rcvid, MSG_OK, &msg, sizeof(msg));
- currentCtime = time(NULL);
- ctime_r(¤tCtime, currentDate);
- fprintf(msgLogHandle, "%s %d/%d/%d sent: %s \n", currentDate, nd, pid, chid, msg.m_data);
- fflush(msgLogHandle);
- break;
- case MSG_END:
- //End of message
- MsgReply(rcvid, MSG_END, NULL, NULL);
- break;
- default:
- //error message is logged
- MsgReply(rcvid, MSG_INVALID, &msg, sizeof(msg));
- break;
- }
- }
- fclose(pidHandle);
- //Usually won't get to this part
- MsgReply(rcvid, EOK, &msg, sizeof (msg));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement