Process message improved.
npipe locking.
--- a/syslog_in_npipe.c Wed Mar 29 08:45:17 2006 +0200
+++ b/syslog_in_npipe.c Wed Mar 29 08:45:32 2006 +0200
@@ -7,6 +7,8 @@
#include <sys/stat.h> // Per crides de fitxer
#include <fcntl.h> // Per crides de fitxer
#include <stdbool.h> // Per les macros bool,true,false
+#include <unistd.h> // Pel lockf()
+#include <fcntl.h> // Pel lockf()
#include "rfc3164.h"
@@ -36,11 +38,69 @@
return false;
}
-int main(int argn, char **argv)
+int pipe_server(const char * restrict filename)
{
int fd_entrada;
char missatge[MESSAGE_LENGTH];
int status;
+ struct flock blocking;
+
+ blocking.l_type = F_RDLCK;
+ blocking.l_whence = SEEK_SET;
+ blocking.l_start = 0;
+ blocking.l_len = 0;
+
+ while(true)
+ {
+ /* Obrim la named fifo síncrona. */
+ fd_entrada = open(filename, O_RDONLY);
+ if (fd_entrada < 0) {
+ printf("Error opening the named pipe: %s\n",
+ strerror(errno));
+ return 1;
+ }
+
+ status = fcntl(fd_entrada, F_SETLKW, &blocking);
+ if (fd_entrada < 0) {
+ printf("Error locking the named pipe: %s\n",
+ strerror(errno));
+ return 1;
+ }
+
+ while ((status = read(fd_entrada, missatge,
+ MESSAGE_LENGTH +1)) > 0)
+ {
+ process_message(missatge);
+ }
+
+ if (status < 0)
+ {
+ printf("Error reading the named pipe: %s\n",
+ strerror(errno));
+ blocking.l_type = F_UNLCK;
+ status = fcntl(fd_entrada, F_SETLKW, &blocking);
+ if (fd_entrada < 0) {
+ printf("Error unlocking the named pipe: %s\n",
+ strerror(errno));
+ abort();
+ }
+ close (fd_entrada);
+ return 1;
+ }
+ }
+
+ blocking.l_type = F_UNLCK;
+ status = fcntl(fd_entrada, F_SETLKW, &blocking);
+ if (fd_entrada < 0) {
+ printf("Error unlocking the named pipe: %s\n", strerror(errno));
+ abort();
+ }
+
+ close (fd_entrada);
+}
+
+int main(int argn, char **argv)
+{
/* Processem els paràmetres d'entrada */
if (argn != 2) {
@@ -56,30 +116,6 @@
abort();
};
- /* Obrim la named fifo síncrona. */
- fd_entrada = open(argv[1], O_RDONLY);
- if (fd_entrada < 0) {
- printf("Error opening the named pipe: %s\n",
- strerror(errno));
- return 1;
- }
- while ((status = read(fd_entrada, missatge, MESSAGE_LENGTH +1)) > 0)
- {
- /* Dummy */
- printf(missatge);
- printf("\n");
- }
-
- if (status < 0)
- {
- printf("Error reading the named pipe: %s\n",
- strerror(errno));
- close (fd_entrada);
- return 1;
- }
-
- close (fd_entrada);
-
- return 0;
+ return pipe_server(argv[1]);
}