The open() is done without mode_t mode.
#include <unistd.h> // Per les crides a fitxer
#include <stdio.h> // Per l'I/O de stdin/stdout
#include <errno.h> // Pels errors de les crides a fitxer
#include <string.h> // Per strerror()
#include <stdlib.h> // Per abort()
#include <sys/types.h> // Per crides de fitxer
#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"
#include "syslog.h"
void showHelp(const char * restrict program)
{
printf("Usage: %s <named_fifo>\n", program);
}
bool isNamedPipe(const char * restrict path)
{
struct stat tmpStatus;
int result;
result = stat(path, &tmpStatus);
if (result == -1)
{
fprintf(stderr, "Error trying to stat the file: %s\n",
strerror(errno));
abort();
}
if (S_ISFIFO(tmpStatus.st_mode))
return true;
return false;
}
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) {
fprintf(stderr, "Error opening the named pipe: %s\n",
strerror(errno));
return 1;
}
status = fcntl(fd_entrada, F_SETLKW, &blocking);
if (fd_entrada < 0) {
fprintf(stderr, "Error locking the named pipe: %s\n",
strerror(errno));
return 1;
}
while ((status = read(fd_entrada, missatge,
MESSAGE_LENGTH)) > 0)
{
process_message(missatge);
/* Debug */
if(!strcmp(missatge,"close"))
{
/* Code duplication !! */
blocking.l_type = F_UNLCK;
status = fcntl(fd_entrada, F_SETLKW, &blocking);
if (fd_entrada < 0) {
fprintf(stderr,
"Error unlocking the named "
"pipe: %s\n",
strerror(errno));
abort();
}
close (fd_entrada);
/* End of code duplication */
return 0;
}
write(1, missatge, status);
}
if (status < 0)
{
fprintf(stderr, "Error reading the named pipe: %s\n",
strerror(errno));
/* Code duplication !! */
blocking.l_type = F_UNLCK;
status = fcntl(fd_entrada, F_SETLKW, &blocking);
if (fd_entrada < 0) {
fprintf(stderr,
"Error unlocking the named pipe: %s\n",
strerror(errno));
abort();
}
close (fd_entrada);
/* End of code duplication */
return 1;
}
/* Code duplication !! */
blocking.l_type = F_UNLCK;
status = fcntl(fd_entrada, F_SETLKW, &blocking);
if (fd_entrada < 0) {
fprintf(stderr,
"Error unlocking the named pipe: %s\n",
strerror(errno));
abort();
}
close (fd_entrada);
/* End of code duplication */
}
}
int main(int argn, char **argv)
{
/* Processem els paràmetres d'entrada */
if (argn != 2) {
showHelp(argv[0]);
return 2;
}
/* Comprovem que existeix i és una named pipe */
/* !!! */
if(!isNamedPipe(argv[1])) // Abortarà si falla
{
fprintf(stderr, "The file is not of a named pipe.\n");
abort();
};
program_ignore_hup();
return pipe_server(argv[1]);
}