--- /dev/null
+/* BarCode.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program barcode
+ * CGI for barcode generation
+ *
+ * Author: Simone Piccardi
+ * Jun. 2002
+ *
+ * Usage: cgi-bin for apache.
+ * Called by downloading something like:
+ * http://localhost/cgi-bin/barcode?string
+ * where string is the code to be converted
+ *
+ * $Id: BarCode.c,v 1.9 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <sys/stat.h> /* stat deinitiions */
+#include <unistd.h> /* include unix standard library */
+/* */
+#include <stdio.h> /* include standard I/O library */
+#include <stdlib.h> /* include standard library */
+#include <string.h> /* include string library */
+#include <wait.h> /* include wait call */
+#include <fcntl.h>
+#include <assert.h>
+#include <time.h>
+
+#include"macros.h"
+
+/* Program begin */
+int main(int argc, char *argv[], char *envp[])
+{
+/*
+ * Variables definition
+ */
+ FILE *pipe[4];
+ FILE *pipein;
+ char *cmd_string[4]={
+ "pnmtopng",
+ "pnmmargin -white 10",
+ "pnmcrop",
+ "gs -sDEVICE=ppmraw -sOutputFile=- -sNOPAUSE -q - -c showpage -c quit"
+ };
+ char content[]="Content-type: image/png\n\n";
+ int i;
+ /* write mime-type to stdout */
+ write(STDOUT_FILENO, content, strlen(content));
+ /* execute chain of command */
+ for (i=0; i<4; i++) {
+ pipe[i] = popen(cmd_string[i], "w");
+ dup2(fileno(pipe[i]), STDOUT_FILENO);
+ }
+ /* create barcode (in PS) */
+ pipein = popen("barcode", "w");
+ /* send barcode string to barcode program */
+ write(fileno(pipein), argv[1], strlen(argv[1]));
+ pclose(pipein);
+ /* close all pipes (in reverse order) */
+ for (i=4; i==0; i--) {
+ pclose((pipe[i]));
+ }
+ exit(0);
+}
--- /dev/null
+/* BarCodePage.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program barcode
+ * CGI for barcode generation
+ *
+ * Author: Simone Piccardi
+ * Jun. 2002
+ *
+ * Usage: cgi-bin for apache.
+ * Called by downloading something like:
+ * http://localhost/cgi-bin/barcode?string
+ * where string is the code to be converted
+ *
+ * $Id: BarCodePage.c,v 1.4 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <sys/stat.h> /* stat deinitiions */
+#include <unistd.h> /* include unix standard library */
+#include <stdio.h> /* include standard I/O library */
+#include <stdlib.h> /* include standard library */
+#include <string.h> /* include string library */
+#include <wait.h> /* include wait call */
+#include <fcntl.h>
+#include <assert.h>
+#include <time.h>
+
+#include"macros.h"
+void WriteMess(char *mess);
+
+/* Program begin */
+int main(int argc, char *argv[], char *envp[])
+{
+/*
+ * Variables definition
+ */
+ pid_t pid;
+ int retval;
+ int pipein[2];
+ int pipeout[2];
+ char content[]="Content-type: image/jpeg\n\n";
+ char size[]="-pA9";
+ /*
+ * Begin
+ */
+ /* create two pipes, pipein and pipeout, to handle communication */
+ if ( (retval = pipe(pipein)) ) {
+ WriteMess("input pipe creation error");
+ exit(0);
+ }
+ if ( (retval = pipe(pipeout)) ) {
+ WriteMess("output pipe creation error");
+ exit(0);
+ }
+ /* First fork: use child to run barcode program */
+ if ( (pid = fork()) == -1 ) {
+ WriteMess("child creation error");
+ exit(0);
+ }
+ /* if child */
+ if (pid == 0) {
+ /*
+ * Child exec barcode program, that take input (string to encode)
+ * from pipein, remapped to stdin, and write the output (a PS
+ * image) to stdout, remapped to pipeout
+ */
+ close(pipein[1]); /* close output side of input pipe */
+ dup2(pipein[0], STDIN_FILENO); /* remap stdin in pipe input */
+ close(pipeout[0]);
+ dup2(pipeout[1], STDOUT_FILENO); /* remap stdout in pipe output */
+ execlp("barcode", "barcode", size, NULL);
+ }
+ /*
+ * Parent write string to pipe input and close it,
+ * then wait child execution and results form pipeout,
+ * then fork to convert PS to JPEG using gs
+ */
+ close(pipein[0]); /* close input side of input pipe */
+ write(pipein[1], argv[1], strlen(argv[1]));
+ close(pipein[1]);
+ waitpid(pid, NULL, 0);
+ /* Second fork: use child to run ghostscript*/
+ if ( (pid = fork()) == -1) {
+ WriteMess("child creation error");
+ exit(0);
+ }
+ /* second child, convert PS to JPEG */
+ if (pid == 0) {
+ close(pipeout[1]); /* close write end */
+ dup2(pipeout[0], STDIN_FILENO); /* remap read end to stdin */
+ /* send mime type */
+ write(STDOUT_FILENO, content, strlen(content));
+ execlp("gs", "gs", "-q", "-sDEVICE=jpeg", "-sOutputFile=-", "-", NULL);
+ }
+ /* still parent */
+ close(pipeout[1]);
+ waitpid(pid, NULL, 0);
+ exit(0);
+}
+/*
+ * Routine to produce an HTML error message on output
+ */
+void WriteMess(char *mess)
+{
+ printf("Content-type: text/html\n\n");
+ perror(mess);
+ printf("<br>\n");
+}
--- /dev/null
+/* DirMonitor.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File DirMonitor:
+ *
+ * An example for shared memory use: monitor a directory status,
+ * saving data in a shared memory segment
+ *
+ * Author: S. Piccardi Jan. 2003
+ *
+ * $Id: DirMonitor.c,v 1.8 2003/05/02 09:55:13 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h> /* directory */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h>
+
+#include "Gapil.h"
+#include "macros.h"
+
+/* Help printing routine */
+void usage(void);
+/* computation function for DirScan */
+int ComputeValues(struct dirent * direntry);
+void HandSIGTERM(int signo);
+
+/* global variables for shared memory segment */
+struct DirProp {
+ int tot_size;
+ int tot_files;
+ int tot_regular;
+ int tot_fifo;
+ int tot_link;
+ int tot_dir;
+ int tot_block;
+ int tot_char;
+ int tot_sock;
+} *shmptr;
+key_t key;
+int mutex;
+
+int main(int argc, char *argv[])
+{
+ int i, pause = 10;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hp:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'p': /* set pause (in sec.) */
+ pause = strtol(optarg, NULL, 10);
+ break;
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if ((argc - optind) != 1) { /* There must be remaing parameters */
+ printf("Wrong number of arguments %d\n", argc - optind);
+ usage();
+ }
+ if (chdir(argv[1])) { /* chdir to be sure dir exist */
+ perror("Cannot find directory to monitor");
+ exit(1);
+ }
+ Signal(SIGTERM, HandSIGTERM); /* set handlers for termination */
+ Signal(SIGINT, HandSIGTERM);
+ Signal(SIGQUIT, HandSIGTERM);
+ key = ftok("~/gapil/sources/DirMonitor.c", 1); /* define a key, use dir */
+ shmptr = ShmCreate(key, 4096, 0666, 0); /* get a shared memory segment */
+ if (!shmptr) {
+ perror("Cannot create shared memory");
+ exit(1);
+ }
+ if ((mutex = MutexCreate(key)) == -1) { /* get a Mutex */
+ perror("Cannot create mutex");
+ exit(1);
+ }
+ /* main loop, monitor directory properties each 10 sec */
+ daemon(1, 0); /* demonize process, staying in monitored dir */
+ while (1) {
+ MutexLock(mutex); /* lock shared memory */
+ memset(shmptr, 0, sizeof(struct DirProp)); /* erase previous data */
+ DirScan(argv[1], ComputeValues); /* execute scan */
+ MutexUnlock(mutex); /* unlock shared memory */
+ sleep(pause); /* sleep until next watch */
+ }
+}
+/*
+ * Routine to compute directory properties inside DirScan
+ */
+int ComputeValues(struct dirent * direntry)
+{
+ struct stat data;
+ stat(direntry->d_name, &data); /* get stat data */
+ shmptr->tot_size += data.st_size;
+ shmptr->tot_files++;
+ if (S_ISREG(data.st_mode)) shmptr->tot_regular++;
+ if (S_ISFIFO(data.st_mode)) shmptr->tot_fifo++;
+ if (S_ISLNK(data.st_mode)) shmptr->tot_link++;
+ if (S_ISDIR(data.st_mode)) shmptr->tot_dir++;
+ if (S_ISBLK(data.st_mode)) shmptr->tot_block++;
+ if (S_ISCHR(data.st_mode)) shmptr->tot_char++;
+ if (S_ISSOCK(data.st_mode)) shmptr->tot_sock++;
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program myls: list file in a directory \n");
+ printf("Usage:\n");
+ printf(" DirMonitor [-h] [-p sec] dirname \n");
+ printf(" -h print this help\n");
+ printf(" -p sec set watch interval to sec seconds \n");
+ exit(1);
+}
+/*
+ * Signal Handler to manage termination
+ */
+void HandSIGTERM(int signo) {
+ MutexLock(mutex);
+ debug("Terminated by %s\n", strsignal(signo));
+ ShmRemove(key, shmptr);
+ MutexRemove(mutex);
+ exit(0);
+}
--- /dev/null
+/* DirScan.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File DirScan.c: routine for directory scan
+ *
+ * Author: S. Piccardi Jan. 2003
+ *
+ * $Id: DirScan.c,v 1.4 2003/05/02 09:55:13 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h> /* directory */
+#include <stdlib.h> /* C standard library */
+#include <stdio.h>
+#include <unistd.h>
+
+/*
+ * Function DirScan:
+ *
+ * Scan all entries in a directory, executing the provided function
+ * on each one.
+ *
+ * Input: the directory name and a computation function
+ * Return: 0 if OK, -1 on errors
+ */
+int DirScan(char * dirname, int(*compute)(struct dirent *))
+{
+ DIR * dir;
+ struct dirent *direntry;
+ int fd;
+
+ if ( (dir = opendir(dirname)) == NULL) { /* oper directory */
+ printf("Opening %s\n", dirname); /* on error print messages */
+ perror("Cannot open directory"); /* and then return */
+ return -1;
+ }
+ fd = dirfd(dir); /* get file descriptor */
+ fchdir(fd); /* change directory */
+ /* loop on directory entries */
+ while ( (direntry = readdir(dir)) != NULL) { /* read entry */
+ if (compute(direntry)) { /* execute function on it */
+ return -1; /* on error return */
+ }
+ }
+ closedir(dir);
+ return 0;
+}
--- /dev/null
+/* ElemEchoTCPClient.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program ElemEchoTCPClient.c
+ * Simple TCP client for echo service (port 7)
+ *
+ * Author: Simone Piccardi
+ * Jun. 2001
+ *
+ * Usage: echo -h give all info's
+ *
+ * $Id: ElemEchoTCPClient.c,v 1.8 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <unistd.h> /* include unix standard library */
+#include <arpa/inet.h> /* IP addresses conversion utiliites */
+#include <sys/socket.h> /* socket library */
+#include <stdio.h> /* include standard I/O library */
+
+#define MAXLINE 256
+void usage(void);
+void ClientEcho(FILE * filein, int socket);
+
+/* Program begin */
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int sock_fd, i;
+ struct sockaddr_in serv_add;
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* create socket */
+ if ( (sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("Socket creation error");
+ return -1;
+ }
+ /* initialize address */
+ memset((void *) &serv_add, 0, sizeof(serv_add)); /* clear server address */
+ serv_add.sin_family = AF_INET; /* address type is INET */
+ serv_add.sin_port = htons(7); /* echo port is 7 */
+ /* build address using inet_pton */
+ if ( (inet_pton(AF_INET, argv[optind], &serv_add.sin_addr)) <= 0) {
+ perror("Address creation error");
+ return -1;
+ }
+ /* extablish connection */
+ if (connect(sock_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
+ perror("Connection error");
+ return -1;
+ }
+ /* read daytime from server */
+ ClientEcho(stdin, sock_fd);
+ /* normal exit */
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Take daytime from a remote host \n");
+ printf("Usage:\n");
+ printf(" daytime [-h] [-v] [host in dotted decimal form] \n");
+ printf(" -v set verbosity on\n");
+ printf(" -h print this help\n");
+ exit(1);
+}
+
+void ClientEcho(FILE * filein, int socket)
+{
+ char sendbuff[MAXLINE], recvbuff[MAXLINE];
+ int nread;
+ while (fgets(sendbuff, MAXLINE, filein) != NULL) {
+ FullWrite(socket, sendbuff, strlen(sendbuff));
+ nread = FullRead(socket, recvbuff, strlen(sendbuff));
+ recvbuff[nread] = 0;
+ fputs(recvbuff, stdout);
+ }
+ return;
+}
--- /dev/null
+/* ElemEchoTCPServer.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program echod
+ * Elementary TCP server for echo service (port 7)
+ *
+ * Author: Simone Piccardi
+ * Jun. 2001
+ *
+ * Usage: echod -h give all info
+ *
+ * $Id: ElemEchoTCPServer.c,v 1.7 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <unistd.h> /* include unix standard library */
+#include <arpa/inet.h> /* IP addresses conversion utiliites */
+#include <sys/socket.h> /* socket library */
+#include <stdio.h> /* include standard I/O library */
+#include <time.h>
+
+
+#define BACKLOG 10
+#define MAXLINE 256
+
+/* Subroutines declaration */
+void usage(void);
+void ServEcho(int sockfd);
+/* Program beginning */
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int list_fd, conn_fd;
+ pid_t pid;
+ struct sockaddr_in serv_add;
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ int i;
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* create socket */
+ if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("Socket creation error");
+ exit(-1);
+ }
+ /* initialize address */
+ memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
+ serv_add.sin_family = AF_INET; /* address type is INET */
+ serv_add.sin_port = htons(7); /* echo port is 7 */
+ serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
+ /* bind socket */
+ if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
+ perror("bind error");
+ exit(-1);
+ }
+ /* listen on socket */
+ if (listen(list_fd, BACKLOG) < 0 ) {
+ perror("listen error");
+ exit(-1);
+ }
+ /* handle echo to client */
+ while (1) {
+ /* accept connection */
+ if ( (conn_fd = accept(list_fd, NULL, NULL)) < 0) {
+ perror("accept error");
+ exit(-1);
+ }
+ /* fork to handle connection */
+ if ( (pid = fork()) < 0 ){
+ perror("fork error");
+ exit(-1);
+ }
+ if (pid == 0) { /* child */
+ close(list_fd); /* close listening socket */
+ SockEcho(conn_fd); /* handle echo */
+ exit(0);
+ } else { /* parent */
+ close(conn_fd); /* close connected socket */
+ }
+ }
+ /* normal exit, never reached */
+ exit(0);
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Elementary echo server\n");
+ printf("Usage:\n");
+ printf(" echod [-h] \n");
+ printf(" -h print this help\n");
+ exit(1);
+}
+/*
+ * routine to handle echo for connection
+ */
+void ServEcho(int sockfd) {
+ char buffer[MAXLINE];
+ int nread, nwrite;
+
+ /* main loop, reading 0 char means client close connection */
+ while ( (nread = read(sockfd, buffer, MAXLINE)) != 0) {
+ printf("Letti %d bytes, %s ", nread, buffer);
+ nwrite = FullWrite(sockfd, buffer, nread);
+ }
+ return;
+}
--- /dev/null
+/* ErrCode.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program ErrCode.c:
+ * Print error code MACRO and messages
+ *
+ * Author: Simone Piccardi
+ * Sep. 2001
+ *
+ * Usage: errcode -h give all info's
+ *
+ * $Id: ErrCode.c,v 1.7 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+#include <limits.h> /* system limits values */
+
+/* Help printing routine */
+void usage(void);
+
+/* Array for code number <=> code macro name */
+char * err_code[] = {
+"SUCCESS ", /* 0 Success */
+"EPERM ", /* 1 Operation not permitted */
+"ENOENT ", /* 2 No such file or directory */
+"ESRCH ", /* 3 No such process */
+"EINTR ", /* 4 Interrupted system call */
+"EIO ", /* 5 I/O error */
+"ENXIO ", /* 6 No such device or address */
+"E2BIG ", /* 7 Arg list too long */
+"ENOEXEC ", /* 8 Exec format error */
+"EBADF ", /* 9 Bad file number */
+"ECHILD ", /* 10 No child processes */
+"EAGAIN ", /* 11 Try again */
+"ENOMEM ", /* 12 Out of memory */
+"EACCES ", /* 13 Permission denied */
+"EFAULT ", /* 14 Bad address */
+"ENOTBLK ", /* 15 Block device required */
+"EBUSY ", /* 16 Device or resource busy */
+"EEXIST ", /* 17 File exists */
+"EXDEV ", /* 18 Cross-device link */
+"ENODEV ", /* 19 No such device */
+"ENOTDIR ", /* 20 Not a directory */
+"EISDIR ", /* 21 Is a directory */
+"EINVAL ", /* 22 Invalid argument */
+"ENFILE ", /* 23 File table overflow */
+"EMFILE ", /* 24 Too many open files */
+"ENOTTY ", /* 25 Not a typewriter */
+"ETXTBSY ", /* 26 Text file busy */
+"EFBIG ", /* 27 File too large */
+"ENOSPC ", /* 28 No space left on device */
+"ESPIPE ", /* 29 Illegal seek */
+"EROFS ", /* 30 Read-only file system */
+"EMLINK ", /* 31 Too many links */
+"EPIPE ", /* 32 Broken pipe */
+"EDOM ", /* 33 Math argument out of domain of func */
+"ERANGE ", /* 34 Math result not representable */
+"EDEADLK ", /* 35 Resource deadlock would occur */
+"ENAMETOOLONG ", /* 36 File name too long */
+"ENOLCK ", /* 37 No record locks available */
+"ENOSYS ", /* 38 Function not implemented */
+"ENOTEMPTY ", /* 39 Directory not empty */
+"ELOOP ", /* 40 Too many symbolic links encountered */
+"EWOULDBLOCK ", /* EAGAIN Operation would block */
+"ENOMSG ", /* 42 No message of desired type */
+"EIDRM ", /* 43 Identifier removed */
+"ECHRNG ", /* 44 Channel number out of range */
+"EL2NSYNC ", /* 45 Level 2 not synchronized */
+"EL3HLT ", /* 46 Level 3 halted */
+"EL3RST ", /* 47 Level 3 reset */
+"ELNRNG ", /* 48 Link number out of range */
+"EUNATCH ", /* 49 Protocol driver not attached */
+"ENOCSI ", /* 50 No CSI structure available */
+"EL2HLT ", /* 51 Level 2 halted */
+"EBADE ", /* 52 Invalid exchange */
+"EBADR ", /* 53 Invalid request descriptor */
+"EXFULL ", /* 54 Exchange full */
+"ENOANO ", /* 55 No anode */
+"EBADRQC ", /* 56 Invalid request code */
+"EBADSLT ", /* 57 Invalid slot */
+"EDEADLOCK ", /* EDEADLK */
+"EBFONT ", /* 59 Bad font file format */
+"ENOSTR ", /* 60 Device not a stream */
+"ENODATA ", /* 61 No data available */
+"ETIME ", /* 62 Timer expired */
+"ENOSR ", /* 63 Out of streams resources */
+"ENONET ", /* 64 Machine is not on the network */
+"ENOPKG ", /* 65 Package not installed */
+"EREMOTE ", /* 66 Object is remote */
+"ENOLINK ", /* 67 Link has been severed */
+"EADV ", /* 68 Advertise error */
+"ESRMNT ", /* 69 Srmount error */
+"ECOMM ", /* 70 Communication error on send */
+"EPROTO ", /* 71 Protocol error */
+"EMULTIHOP ", /* 72 Multihop attempted */
+"EDOTDOT ", /* 73 RFS specific error */
+"EBADMSG ", /* 74 Not a data message */
+"EOVERFLOW ", /* 75 Value too large for defined data type */
+"ENOTUNIQ ", /* 76 Name not unique on network */
+"EBADFD ", /* 77 File descriptor in bad state */
+"EREMCHG ", /* 78 Remote address changed */
+"ELIBACC ", /* 79 Can not access a needed shared library */
+"ELIBBAD ", /* 80 Accessing a corrupted shared library */
+"ELIBSCN ", /* 81 .lib section in a.out corrupted */
+"ELIBMAX ", /* 82 Attempting to link in too many shared libraries */
+"ELIBEXEC ", /* 83 Cannot exec a shared library directly */
+"EILSEQ ", /* 84 Illegal byte sequence */
+"ERESTART ", /* 85 Interrupted system call should be restarted */
+"ESTRPIPE ", /* 86 Streams pipe error */
+"EUSERS ", /* 87 Too many users */
+"ENOTSOCK ", /* 88 Socket operation on non-socket */
+"EDESTADDRREQ ", /* 89 Destination address required */
+"EMSGSIZE ", /* 90 Message too long */
+"EPROTOTYPE ", /* 91 Protocol wrong type for socket */
+"ENOPROTOOPT ", /* 92 Protocol not available */
+"EPROTONOSUPPORT", /* 93 Protocol not supported */
+"ESOCKTNOSUPPORT", /* 94 Socket type not supported */
+"EOPNOTSUPP ", /* 95 Operation not supported on transport endpoint */
+"EPFNOSUPPORT ", /* 96 Protocol family not supported */
+"EAFNOSUPPORT ", /* 97 Address family not supported by protocol */
+"EADDRINUSE ", /* 98 Address already in use */
+"EADDRNOTAVAIL ", /* 99 Cannot assign requested address */
+"ENETDOWN ", /* 100 Network is down */
+"ENETUNREACH ", /* 101 Network is unreachable */
+"ENETRESET ", /* 102 Network dropped connection because of reset */
+"ECONNABORTED ", /* 103 Software caused connection abort */
+"ECONNRESET ", /* 104 Connection reset by peer */
+"ENOBUFS ", /* 105 No buffer space available */
+"EISCONN ", /* 106 Transport endpoint is already connected */
+"ENOTCONN ", /* 107 Transport endpoint is not connected */
+"ESHUTDOWN ", /* 108 Cannot send after transport endpoint shutdown */
+"ETOOMANYREFS ", /* 109 Too many references: cannot splice */
+"ETIMEDOUT ", /* 110 Connection timed out */
+"ECONNREFUSED ", /* 111 Connection refused */
+"EHOSTDOWN ", /* 112 Host is down */
+"EHOSTUNREACH ", /* 113 No route to host */
+"EALREADY ", /* 114 Operation already in progress */
+"EINPROGRESS ", /* 115 Operation now in progress */
+"ESTALE ", /* 116 Stale NFS file handle */
+"EUCLEAN ", /* 117 Structure needs cleaning */
+"ENOTNAM ", /* 118 Not a XENIX named type file */
+"ENAVAIL ", /* 119 No XENIX semaphores available */
+"EISNAM ", /* 120 Is a named type file */
+"EREMOTEIO ", /* 121 Remote I/O error */
+"EDQUOT ", /* 122 Quota exceeded */
+"ENOMEDIUM ", /* 123 No medium found */
+"EMEDIUMTYPE " /* 124 Wrong medium type */
+};
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i, err;
+ int label = 0;
+ int message = 0;
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hlm")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case 'l': /* unrecognized options */
+ printf("Label printing\n");
+ label = 1;
+ break;
+ case 'm': /* unrecognized options */
+ printf("Message printing\n");
+ message = 1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if (optind == argc) {
+ usage();
+ }
+ /* convert string to number */
+ err = strtol(argv[optind], NULL, 10);
+ /* testing error condition on conversion */
+ if (err==LONG_MIN) {
+ perror("Underflow on error code");
+ return 1;
+ } else if (err==LONG_MIN) {
+ perror("Overflow on error code");
+ return 1;
+ }
+ /* conversion is fine */
+ if (message) {
+ printf("Error message for %d is %s\n", err, strerror(err));
+ }
+ if (label) {
+ printf("Error label for %d is %s\n", err, err_code[err]);
+ }
+ if ( (!label)&&(!message) ) {
+ usage();
+ }
+ /* normal exit */
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Print error code message or macro label \n");
+ printf("Usage:\n");
+ printf(" daytime [-h] [-l] [-m] error code \n");
+ printf(" -m print error messages\n");
+ printf(" -l print error code label\n");
+ printf(" -h print this help\n");
+ exit(1);
+}
--- /dev/null
+/* Flock.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * Program Flock.c:
+ * Program to test file locking
+ *
+ * Author: Simone Piccardi
+ * Nov. 2002
+ *
+ * Usage: flock -h give all info's
+ *
+ * $Id: Flock.c,v 1.5 2003/05/02 09:55:13 piccardi Exp $
+ *
+ *****************************************************************************/
+/*
+ * Include needed headers
+ */
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+#include <fcntl.h> /* string functions */
+/* user defined header */
+#include "macros.h" /* some useful macros */
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int type = F_UNLCK; /* lock type: default to unlock (invalid) */
+ off_t start = 0; /* start of the locked region: default to 0 */
+ off_t len = 0; /* length of the locked region: default to 0 */
+ int fd, res, i; /* internal variables */
+ int bsd = 0; /* semantic type: default to POSIX */
+ int cmd = F_SETLK; /* lock command: default to non-blocking */
+ struct flock lock; /* file lock structure */
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hs:l:wrbf")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case 's': /* take start point of the lock */
+ start = strtol(optarg, NULL, 10); /* convert input */
+ break;
+ case 'l': /* take length of the lock */
+ len = strtol(optarg, NULL, 10); /* convert input */
+ break;
+ case 'w': /* set type to write lock */
+ type = F_WRLCK;
+ break;
+ case 'r': /* set type to read lock */
+ type = F_RDLCK;
+ break;
+ case 'b': /* set lock to blocking */
+ cmd = F_SETLKW;
+ break;
+ case 'f': /* enable BSD semantic */
+ bsd = 1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if ((argc - optind) != 1) { /* There must be remaing parameters */
+ printf("Wrong number of arguments %d\n", argc - optind);
+ usage();
+ }
+ if (type == F_UNLCK) { /* There must be a -w or -r option set */
+ printf("You should set a read or a write lock\n");
+ usage();
+ }
+ fd = open(argv[optind], O_RDONLY); /* open the file to be locked */
+ if (fd < 0) { /* on error exit */
+ perror("Wrong filename");
+ exit(1);
+ }
+ /* do lock */
+ if (bsd) { /* if BSD locking */
+ /* rewrite cmd for suitables flock operation values */
+ if (cmd == F_SETLK) { /* if no-blocking */
+ cmd = LOCK_NB; /* set the value for flock operation */
+ } else { /* else */
+ cmd = 0; /* default is null */
+ }
+ if (type == F_RDLCK) cmd |= LOCK_SH; /* set for shared lock */
+ if (type == F_WRLCK) cmd |= LOCK_EX; /* set for exclusive lock */
+ res = flock(fd, cmd); /* esecute lock */
+ } else { /* if POSIX locking */
+ /* setting flock structure */
+ lock.l_type = type; /* set type: read or write */
+ lock.l_whence = SEEK_SET; /* start from the beginning of the file */
+ lock.l_start = start; /* set the start of the locked region */
+ lock.l_len = len; /* set the length of the locked region */
+ res = fcntl(fd, cmd, &lock); /* do lock */
+ }
+ /* check lock results */
+ if (res) { /* on error exit */
+ perror("Failed lock");
+ exit(1);
+ } else { /* else write message */
+ printf("Lock acquired\n");
+ }
+ pause(); /* stop the process, use a signal to exit */
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program flock: lock a region of a file \n");
+ printf("Usage:\n");
+ printf(" forktest [-h] [-s start] [-l len] [-w|-r] filename \n");
+ printf(" -h print this help\n");
+ printf(" -s start region starting byte\n");
+ printf(" -l len region length (0 means all file)\n");
+ printf(" -w write lock\n");
+ printf(" -r read lock\n");
+ printf(" -b block when locking impossible\n");
+ printf(" -f enable BSD semantic\n");
+ exit(1);
+}
--- /dev/null
+/* ForkTest.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program ForkTest.c:
+ * Program to test process creation
+ *
+ * Author: Simone Piccardi
+ * Sep. 2001
+ *
+ * Usage: forktest -h give all info's
+ *
+ * $Id: ForkTest.c,v 1.10 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+
+#include "Gapil.h"
+#include "macros.h"
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int nchild, i;
+ pid_t pid;
+ int wait_child = 0;
+ int wait_parent = 0;
+ int wait_end = 0;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hsp:c:e:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case 'c': /* take wait time for childen */
+ wait_child = strtol(optarg, NULL, 10); /* convert input */
+ break;
+ case 'p': /* take wait time for childen */
+ wait_parent = strtol(optarg, NULL, 10); /* convert input */
+ break;
+ case 'e': /* take wait before parent exit */
+ wait_end = strtol(optarg, NULL, 10); /* convert input */
+ break;
+ case 's':
+ Signal(SIGCHLD, HandSigCHLD);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* There must be remaing parameters */
+ if (optind == argc) {
+ usage();
+ }
+ nchild = atoi(argv[optind]);
+ printf("Process %d: forking %d child\n", getpid(), nchild);
+ /* loop to fork children */
+ for (i=0; i<nchild; i++) {
+ if ( (pid = fork()) < 0) {
+ /* on error exit */
+ printf("Error on %d child creation, %s\n", i+1, strerror(errno));
+ exit(-1);
+ }
+ if (pid == 0) { /* child */
+ printf("Child %d successfully executing\n", ++i);
+ if (wait_child) sleep(wait_child);
+ printf("Child %d, parent %d, exiting\n", i, getppid());
+ exit(0);
+ } else { /* parent */
+ printf("Spawned %d child, pid %d \n", i+1, pid);
+ if (wait_parent) sleep(wait_parent);
+ printf("Go to next child \n");
+ }
+ }
+ /* normal exit */
+ if (wait_end) sleep(wait_end);
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program forktest: fork a given number of child \n");
+ printf("Usage:\n");
+ printf(" forktest [-h] [-p sec] [-c sec] [-e sec] child to fork \n");
+ printf(" -h print this help\n");
+ printf(" -s install signal handler\n");
+ printf(" -p sec wait sec seconds before next fork\n");
+ printf(" -c sec wait sec seconds before child termination\n");
+ printf(" -e sec wait sec seconds before parent return\n");
+
+ exit(1);
+}
--- /dev/null
+/* FortuneClient.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program fortune
+ * Fortune client
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: fortune -h give all info
+ *
+ * $Id: FortuneClient.c,v 1.4 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <unistd.h> /* include unix standard library */
+#include <arpa/inet.h> /* IP addresses conversion utiliites */
+#include <stdio.h> /* include standard I/O library */
+#include <errno.h>
+#include <fcntl.h>
+
+#include "macros.h"
+
+/* Subroutines declaration */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/* Variables definition */
+ int n = 0;
+ char *fortunefilename = "/tmp/fortune.fifo";
+ char line[80];
+ int fifo_server, fifo_client;
+ char fifoname[80];
+ int nread;
+ char buffer[PIPE_BUF];
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ int i;
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hf:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case 'f':
+ fortunefilename = optarg;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ snprintf(fifoname, 80, "/tmp/fortune.%d", getpid()); /* compose name */
+ if (mkfifo(fifoname, 0622)) { /* open client fifo */
+ if (errno!=EEXIST) {
+ perror("Cannot create well known fifo");
+ exit(-1);
+ }
+ }
+ fifo_server = open(fortunefilename, O_WRONLY); /* open server fifo */
+ if (fifo_server < 0) {
+ perror("Cannot open well known fifo");
+ exit(-1);
+ }
+ debug("%s\n", fifoname);
+ nread = write(fifo_server, fifoname, strlen(fifoname)+1); /* write name */
+ close(fifo_server); /* close server fifo */
+ fifo_client = open(fifoname, O_RDONLY); /* open client fifo */
+ if (fifo_client < 0) {
+ perror("Cannot open well known fifo");
+ exit(-1);
+ }
+ nread = read(fifo_client, buffer, sizeof(buffer)); /* read answer */
+ printf("%s", buffer); /* print fortune */
+ close(fifo_client); /* close client */
+ unlink(fifoname); /* remove client fifo */
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Elementary fortune server\n");
+ printf("Usage:\n");
+ printf(" fortune [-h] [-f] \n");
+ printf(" -h print this help\n");
+ printf(" -f filename set file for fortunes\n");
+ exit(1);
+}
--- /dev/null
+/* FortuneParse.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine FortuneParse
+ * parse fortunes from a fortune file
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: int FortuneParse(char *file, char ** fortune, int n);
+ * Read n fortunes from fortune file file, and put it into the
+ * string array fortune
+ *
+ * $Id: FortuneParse.c,v 1.5 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <sys/stat.h> /* */
+#include <unistd.h> /* include unix standard library */
+#include <stdio.h> /* include standard I/O library */
+#include <stdlib.h> /* standard library */
+#include <string.h> /* ANSI C standard string */
+#include <errno.h> /* error definitions */
+#include <fcntl.h> /* */
+
+#include "macros.h"
+
+/* Subroutines declaration */
+extern void usage(void);
+
+int FortuneParse(char *file, char **fortune, int n)
+{
+/* Variables definition */
+ FILE *fortunefile;
+ char line[80];
+ int i, len;
+ /*
+ * fortune file scanning, read string in memory
+ */
+ fortunefile = fopen(file,"r");
+ if (fortunefile == NULL) { /* on open error exit */
+ printf("On file %s\n", file);
+ perror("Cannot open file");
+ exit(-1);
+ }
+ i = 0;
+ do {
+ if (!fgets(line, 80, fortunefile)) {
+ if (feof(fortunefile)) break;
+ perror("Read error");
+ exit(-1);
+ }
+ debug("i=%d, line=%s", i, line);
+ if (line[0]=='%') {
+ if (fortune[i]!=NULL) i++;
+ continue;
+ }
+ len = strlen(line) + 1;
+ if (fortune[i]==NULL) {
+ fortune[i] = malloc(len);
+ strncpy(fortune[i], line, len);
+ } else {
+ fortune[i] = realloc(fortune[i], strlen(fortune[i])+len+1);
+ strncat(fortune[i], line, len);
+ }
+ } while (i<n);
+ return i;
+}
--- /dev/null
+/* FortuneServer.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program fortuned
+ * Fortune server
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: fortuned -h give all info
+ *
+ * $Id: FortuneServer.c,v 1.8 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <sys/stat.h> /* */
+#include <unistd.h> /* include unix standard library */
+#include <stdio.h> /* include standard I/O library */
+#include <stdlib.h> /* standard library */
+#include <string.h> /* ANSI C standard string */
+#include <errno.h> /* errorstring */
+#include <signal.h> /* signals */
+#include <fcntl.h> /* */
+
+#include "macros.h"
+#include "Gapil.h"
+
+/* Subroutines declaration */
+void usage(void);
+void HandSIGTERM(int signo);
+int FortuneParse(char *file, char **fortune, int n);
+
+/* name of well known fifo */
+char *fifoname = "/tmp/fortune.fifo";
+int main(int argc, char *argv[])
+{
+/* Variables definition */
+ int i, n = 0;
+ char *fortunefilename = "/usr/share/games/fortunes/linux";
+ char **fortune;
+ char line[80];
+ int fifo_server, fifo_client;
+ int nread;
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hn:f:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case 'f':
+ fortunefilename = optarg;
+ break;
+ case 'n':
+ n = strtol(optarg, NULL, 10);
+ fortune = (char **) calloc(sizeof(*fortune), n);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if (n==0) usage(); /* if no pool depth exit printing usage info */
+ Signal(SIGTERM, HandSIGTERM); /* set handlers for termination */
+ Signal(SIGINT, HandSIGTERM);
+ Signal(SIGQUIT, HandSIGTERM);
+ i = FortuneParse(fortunefilename, fortune, n); /* parse phrases */
+ for (n=0; n<i; n++) debug("%s%%\n", fortune[n]);
+ /*
+ * Comunication section
+ */
+ if (mkfifo(fifoname, 0622)) { /* create well known fifo if does't exist */
+ if (errno!=EEXIST) {
+ perror("Cannot create well known fifo");
+ exit(1);
+ }
+ }
+ daemon(0, 0);
+ /* open fifo two times to avoid EOF */
+ fifo_server = open(fifoname, O_RDONLY);
+ if (fifo_server < 0) {
+ perror("Cannot open read only well known fifo");
+ exit(1);
+ }
+ if (open(fifoname, O_WRONLY) < 0) {
+ perror("Cannot open write only well known fifo");
+ exit(1);
+ }
+ /* Main body: loop over requests */
+ while (1) {
+ nread = read(fifo_server, line, 79); /* read request */
+ if (nread < 0) {
+ perror("Read Error");
+ exit(1);
+ }
+ line[nread] = 0; /* terminate fifo name string */
+ debug("%s %d\n", line,nread);
+ n = random() % i; /* select random value */
+ debug("fortune[%d]=%s\n", n, fortune[n]);
+ fifo_client = open(line, O_WRONLY); /* open client fifo */
+ if (fifo_client < 0) {
+ debug("Client fifo is %s\n", line);
+ perror("Cannot open");
+ exit(1);
+ }
+ nread = write(fifo_client, /* write phrase */
+ fortune[n], strlen(fortune[n])+1);
+ close(fifo_client); /* close client fifo */
+ }
+ debug("Exiting for unknown reasons\n");
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Elementary fortune server\n");
+ printf("Usage:\n");
+ printf(" fortuned [-h] [-f] -n XXX \n");
+ printf(" -h print this help\n");
+ printf(" -f filename set file for fortunes\n");
+ printf(" -n XXX set pool depth\n");
+ exit(1);
+}
+/*
+ * Signal Handler to manage termination
+ */
+void HandSIGTERM(int signo) {
+ debug("Terminated by %s\n", strsignal(signo));
+ unlink(fifoname);
+ exit(0);
+}
--- /dev/null
+/* FullRead.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine FullRead
+ * Routine to read an exact number of bytes from a socket
+ *
+ * Author: Simone Piccardi
+ * Jun. 2001
+ *
+ * $Id: FullRead.c,v 1.3 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+#include <unistd.h>
+#include <errno.h>
+
+ssize_t FullRead(int fd, void *buf, size_t count)
+{
+ size_t nleft;
+ ssize_t nread;
+
+ nleft = count;
+ while (nleft > 0) { /* repeat until no left */
+ if ( (nread = read(fd, buf, nleft)) < 0) {
+ if (errno == EINTR) { /* if interrupted by system call */
+ continue; /* repeat the loop */
+ } else {
+ return(nread); /* otherwise exit */
+ }
+ } else if (nread == 0) { /* EOF */
+ break; /* break loop here */
+ }
+ nleft -= nread; /* set left to read */
+ buf +=nread; /* set pointer */
+ }
+ return (count - nleft);
+}
+
--- /dev/null
+/* FullWrite.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine FullWrite
+ * Routine to write an exact number of bytes into a socket
+ *
+ * Author: Simone Piccardi
+ * Jun. 2001
+ *
+ * $Id: FullWrite.c,v 1.3 2003/05/02 09:55:13 piccardi Exp $
+ *
+ ****************************************************************/
+#include <unistd.h>
+#include <errno.h>
+
+ssize_t FullWrite(int fd, const void *buf, size_t count)
+{
+ size_t nleft;
+ ssize_t nwritten;
+
+ nleft = count;
+ while (nleft > 0) { /* repeat until no left */
+ if ( (nwritten = write(fd, buf, nleft)) < 0) {
+ if (errno == EINTR) { /* if interrupted by system call */
+ continue; /* repeat the loop */
+ } else {
+ return(nwritten); /* otherwise exit with error */
+ }
+ }
+ nleft -= nwritten; /* set left to write */
+ buf +=nwritten; /* set pointer */
+ }
+ return (count);
+}
+
--- /dev/null
+/* IPCTestId.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program IPCTestId.c:
+ * Program to test IPC identifiers
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: ipctestid -h give all info's
+ *
+ * $Id: IPCTestId.c,v 1.4 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+#include <sys/ipc.h> /* SysV IPC functions */
+#include <sys/msg.h> /* SysV Message Queue */
+#include <sys/sem.h> /* SysV Semaphores */
+#include <sys/shm.h> /* SysV Shared Memory */
+
+#include "macros.h" /* My macros */
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i;
+ int n = 5; /* default is 10 tryes */
+ char type='q'; /* default is use queues */
+ int id;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hqsmn:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case 'q': /* Message Queue */
+ debug("Message Queue\n");
+ type = i;
+ break;
+ case 's': /* Semaphore */
+ debug("Semaphore\n");
+ type = i;
+ break;
+ case 'm': /* Shared Memory */
+ debug("Shared Memory\n");
+ type = i;
+ break;
+ case 'n': /* Number of tryes */
+ debug("Number of tryes\n");
+ n = strtol(optarg, NULL, 10);
+ break;
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ switch (type) {
+ case 'q': /* Message Queue */
+ debug("Message Queue Try\n");
+ for (i=0; i<n; i++) {
+ id = msgget(IPC_PRIVATE, IPC_CREAT|0666);
+ printf("Identifier Value %d \n", id);
+ msgctl(id, IPC_RMID, NULL);
+ }
+ break;
+ case 's': /* Semaphore */
+ debug("Semaphore\n");
+ for (i=0; i<n; i++) {
+ id = semget(IPC_PRIVATE, 1, IPC_CREAT|0666);
+ printf("Identifier Value %d \n", id);
+ semctl(id, 0, IPC_RMID);
+ }
+ break;
+ case 'm': /* Shared Memory */
+ debug("Shared Memory\n");
+ for (i=0; i<n; i++) {
+ id = shmget(IPC_PRIVATE, 1000, IPC_CREAT|0666);
+ printf("Identifier Value %d \n", id);
+ shmctl(id, IPC_RMID, NULL);
+ }
+ break;
+ default: /* should not reached */
+ return -1;
+ }
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program ipctestid : test IPC identifier number assignment\n");
+ printf("Usage:\n");
+ printf(" ipctestid [-h] [-qsm] [-n N] \n");
+ printf(" -h print this help\n");
+ printf(" -q try for message queue identifiers\n");
+ printf(" -s try for semaphore identifiers\n");
+ printf(" -m try for shared memory identifiers\n");
+ printf(" -n XX try XX times\n");
+
+ exit(1);
+}
+
--- /dev/null
+/* LockFile.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File LockFile.h:
+ * Function to manipulate lock files.
+ *
+ * Author: S. Piccardi, Dec 2002
+ *
+ * $Id: LockFile.c,v 1.4 2003/05/02 09:55:14 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h> /* unix standard functions */
+#include <fcntl.h> /* file control (lock) functions */
+/*
+ * Function LockFile:
+ *
+ * Create a lockfile of the given pathname. Fail and exit in case of
+ * error or existence of the same lock file, using unlink do not need
+ * to remove the file.
+ *
+ * Author: Simone Piccardi, Dec. 2002
+ */
+int LockFile(const char* path_name)
+{
+ return open(path_name, O_EXCL|O_CREAT);
+}
+/*
+ * Function UnlockFile:
+ * Remove a lockfile of the given pathname.
+ *
+ * Author: Simone Piccardi, Dec. 2002
+ */
+int UnlockFile(const char* path_name)
+{
+ return unlink(path_name);
+}
--- /dev/null
+/* MQFortuneClient.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program fortuned
+ * Fortune Cleint - Using Message Queues
+ *
+ * Author: Simone Piccardi
+ * Oct. 2002
+ *
+ * Usage: fortune -h give all info
+ *
+ * $Id: MQFortuneClient.c,v 1.4 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <sys/stat.h> /* */
+#include <unistd.h> /* include unix standard library */
+#include <stdio.h> /* include standard I/O library */
+#include <stdlib.h> /* standard library */
+#include <string.h> /* ANSI C standard string */
+#include <errno.h> /* errorstring */
+#include <signal.h> /* signals */
+#include <sys/ipc.h>
+#include <sys/msg.h>
+
+#include "macros.h"
+
+/* Maximum message size */
+#define MSGMAX 8192
+
+/* Subroutines declaration */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/* Variables definition */
+ int i;
+ struct msgbuf_read { /* message struct to ask fortune to server */
+ long mtype; /* message type, must be 1 */
+ long pid; /* message data, must be the pid of the client */
+ } msg_read;
+ struct msgbuf_write { /* message struct to get result from server */
+ long mtype; /* message type, will be the pid of the client*/
+ char mtext[MSGMAX]; /* message data, will be the fortune */
+ } msg_write;
+ int msgid; /* Message queue identifier */
+ key_t key; /* Message queue key */
+ int size; /* message size */
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ usage();
+ return(0);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n", optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /*
+ * Comunication section
+ */
+ key = ftok("./MQFortuneServer.c", 1);
+ msgid = msgget(key, 0);
+ if (msgid < 0) {
+ perror("Cannot find message queue");
+ exit(1);
+ }
+
+ /* Main body: do request and write result */
+ msg_read.mtype = 1; /* type for request is always 1 */
+ msg_read.pid = getpid(); /* use pid for communications */
+ size = sizeof(msg_read.pid);
+ msgsnd(msgid, &msg_read, size, 0); /* send request message */
+ debug("sent request from %d\n", msg_read.pid);
+ msgrcv(msgid, &msg_write, MSGMAX, msg_read.pid, MSG_NOERROR);
+ printf("%s", msg_write.mtext);
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Elementary fortune server\n");
+ printf("Usage:\n");
+ printf(" fortuned [-h] [-f] -n XXX \n");
+ printf(" -h print this help\n");
+ printf(" -f filename set file for fortunes\n");
+ printf(" -n XXX set pool depth\n");
+ exit(1);
+}
--- /dev/null
+/* MQFortuneServer.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program fortuned
+ * Fortune server - Using Message Queues
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: fortuned -h give all info
+ *
+ * $Id: MQFortuneServer.c,v 1.6 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <sys/stat.h> /* */
+#include <unistd.h> /* include unix standard library */
+#include <stdio.h> /* include standard I/O library */
+#include <stdlib.h> /* standard library */
+#include <string.h> /* ANSI C standard string */
+#include <errno.h> /* errorstring */
+#include <signal.h> /* signals */
+#include <sys/ipc.h>
+#include <sys/msg.h>
+
+#include "macros.h"
+#include "Gapil.h"
+
+/* Maximum message size */
+#define MSGMAX 8192
+
+/* Subroutines declaration */
+void usage(void);
+void HandSIGTERM(int signo);
+int FortuneParse(char *file, char **fortune, int n);
+
+int msgid; /* Message queue identifier */
+int main(int argc, char *argv[])
+{
+/* Variables definition */
+ int i, n = 0;
+ char **fortune; /* array of fortune message string */
+ char *fortunefilename = "/usr/share/games/fortunes/linux"; /* file name */
+ struct msgbuf_read { /* message struct to read request from clients */
+ long mtype; /* message type, must be 1 */
+ long pid; /* message data, must be the pid of the client */
+ } msg_read;
+ struct msgbuf_write { /* message struct to write result to clients */
+ long mtype; /* message type, will be the pid of the client*/
+ char mtext[MSGMAX]; /* message data, will be the fortune */
+ } msg_write;
+ key_t key; /* Message queue key */
+ int size; /* message size */
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hn:f:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* print usage infos */
+ usage();
+ return(0);
+ break;
+ case 'f': /* set fortune file name */
+ fortunefilename = optarg;
+ break;
+ case 'n': /* set number of fortune string to use */
+ n = strtol(optarg, NULL, 10);
+ fortune = (char **) calloc(sizeof(*fortune), n);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n", optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if (n==0) usage(); /* if no pool depth exit printing usage info */
+ Signal(SIGTERM, HandSIGTERM); /* set handlers for termination */
+ Signal(SIGINT, HandSIGTERM);
+ Signal(SIGQUIT, HandSIGTERM);
+ i = FortuneParse(fortunefilename, fortune, n); /* parse phrases */
+ for (n=0; n<i; n++) debug("%s%%\n", fortune[n]);
+ /*
+ * Comunication section
+ */
+ key = ftok("./MQFortuneServer.c", 1);
+ msgid = msgget(key, IPC_CREAT|0666);
+ if (msgid < 0) {
+ perror("Cannot create message queue");
+ exit(1);
+ }
+
+ /* Main body: loop over requests */
+ daemon(0, 0);
+ while (1) {
+ msgrcv(msgid, &msg_read, sizeof(int), 1, MSG_NOERROR);
+ debug("received request from %d\n", msg_read.pid);
+ n = random() % i; /* select random value */
+ strncpy(msg_write.mtext, fortune[n], MSGMAX);
+ size = min(strlen(fortune[n])+1, MSGMAX);
+ msg_write.mtype=msg_read.pid; /* use request pid as type */
+ msgsnd(msgid, &msg_write, size, 0);
+ }
+ debug("Exiting for unknown reasons\n");
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Elementary fortune server\n");
+ printf("Usage:\n");
+ printf(" fortuned [-h] [-f] -n XXX \n");
+ printf(" -h print this help\n");
+ printf(" -f filename set file for fortunes\n");
+ printf(" -n NNN set pool depth\n");
+ exit(1);
+}
+/*
+ * Signal Handler to manage termination
+ */
+void HandSIGTERM(int signo) {
+ debug("Terminated by %s\n", strsignal(signo));
+ msgctl(msgid, IPC_RMID, NULL); /* remove message queue */
+ exit(0);
+}
--- /dev/null
+/* Mutex.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File Mutex.c: define a set of functions for mutex manipulation
+ *
+ * Author: S. Piccardi Dec. 2002
+ *
+ * $Id: Mutex.c,v 1.7 2003/05/02 09:55:14 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/sem.h> /* IPC semaphore declarations */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <signal.h> /* signal handling declarations */
+
+#include "Gapil.h"
+/*
+ * Function MutexCreate: create a mutex/semaphore
+ *
+ * First call create a semaphore, using the given key.
+ * We want only one semaphore so we set second argument to 1; third
+ * parameter is the flag argument, and is set to create a semaphore
+ * with R/W privilege for the user.
+ * Second call initialize the semaphore to 1 (unlocked)
+ *
+ * Input: an IPC key value (to create an unique semaphore)
+ * Return: the semaphore id# or -1 on error
+ */
+int MutexCreate(key_t ipc_key)
+{
+ const union semun semunion={1}; /* semaphore union structure */
+ int sem_id, ret;
+ sem_id = semget(ipc_key, 1, IPC_CREAT|0666); /* get semaphore ID */
+ if (sem_id == -1) { /* if error return code */
+ return sem_id;
+ }
+ ret = semctl(sem_id, 0, SETVAL, semunion); /* init semaphore */
+ if (ret == -1) {
+ return ret;
+ }
+ return sem_id;
+}
+/*
+ * Function MutexFind: get the semaphore/mutex Id given the IPC key value
+ *
+ * Input: an IPC key value
+ */
+int MutexFind(key_t ipc_key)
+{
+ return semget(ipc_key, 1, 0);
+}
+/*
+ * Function MutexRead: read the current value of the mutex/semaphore
+ *
+ * Input: a semaphore id #
+ * Return: the semaphore value
+ */
+int MutexRead(int sem_id)
+{
+ return semctl(sem_id, 0, GETVAL);
+}
+/*
+ * Define sembuf structures to lock and unlock the semaphore
+ * (used to implement a mutex)
+ */
+struct sembuf sem_lock={ /* to lock semaphore */
+ 0, /* semaphore number (only one so 0) */
+ -1, /* operation (-1 to use resource) */
+ SEM_UNDO}; /* flag (set for undo at exit) */
+struct sembuf sem_ulock={ /* to unlock semaphore */
+ 0, /* semaphore number (only one so 0) */
+ 1, /* operation (1 to release resource) */
+ SEM_UNDO}; /* flag (in this case 0) */
+/*
+ * Function MutexLock: to lock a mutex/semaphore
+ *
+ * Input: a semaphore id #
+ * Output: semop return code (0 OK, -1 KO)
+ */
+int MutexLock(int sem_id)
+{
+ return semop(sem_id, &sem_lock, 1);
+}
+/*
+ * Function MutexUnlock: to unlock a mutex/semaphore
+ *
+ * Input: a semaphore id #
+ * Return: semop return code (0 OK, -1 KO)
+ */
+int MutexUnlock(int sem_id)
+{
+ return semop(sem_id, &sem_ulock, 1);
+}
+/*
+ * Function MutexRemove: remove a mutex/semaphore
+ *
+ * Input: a semaphore id #
+ * Return: return code of semctl
+ */
+int MutexRemove(int sem_id)
+{
+ return semctl(sem_id, 0, IPC_RMID);
+}
+/*****************************************************************************
+ *
+ * File locking mutex
+ *
+ * Create a mutex usinf file locking. Use file locking to lock a file
+ * as a mutex request, and unlock it as a mutex release.
+ *
+ * Author: S. Piccardi Dec. 2002
+ *
+ *****************************************************************************/
+/*
+ * Function CreateMutex: Create a mutex using file locking.
+ *
+ * Open a new lock file (creating it if not existent, and giving error
+ * otherwise). Is a simple wrapper for open.
+ *
+ * Input: a filename
+ * Output: a file descriptor (>0 OK, -1 KO)
+ */
+int CreateMutex(const char *path_name)
+{
+ return open(path_name, O_EXCL|O_CREAT);
+}
+/*
+ * Function UnlockMutex: unlock a file.
+ *
+ * Open a lock file (failing if not existent). Is a simple wrapper for
+ * open.
+ *
+ * Input: a filename
+ * Output: a return code (>0 OK, -1 KO)
+ */
+int FindMutex(const char *path_name)
+{
+ return open(path_name, O_RDWR);
+}
+/*
+ * Function LockMutex: lock mutex using file locking.
+ *
+ * Input: a mutex (i.e. a file descriptor)
+ * Output: a return code (0 OK, -1 KO)
+ */
+int LockMutex(int fd)
+{
+ struct flock lock; /* file lock structure */
+ /* first open the file (creating it if not existent) */
+ /* set flock structure */
+ lock.l_type = F_WRLCK; /* set type: read or write */
+ lock.l_whence = SEEK_SET; /* start from the beginning of the file */
+ lock.l_start = 0; /* set the start of the locked region */
+ lock.l_len = 0; /* set the length of the locked region */
+ /* do locking */
+ return fcntl(fd, F_SETLKW, &lock);
+}
+/*
+ * Function UnlockMutex: unlock a file.
+ *
+ * Input: a mutex (i.e. a file descriptor)
+ * Output: a return code (0 OK, -1 KO)
+ */
+int UnlockMutex(int fd)
+{
+ struct flock lock; /* file lock structure */
+ /* set flock structure */
+ lock.l_type = F_UNLCK; /* set type: unlock */
+ lock.l_whence = SEEK_SET; /* start from the beginning of the file */
+ lock.l_start = 0; /* set the start of the locked region */
+ lock.l_len = 0; /* set the length of the locked region */
+ /* do locking */
+ return fcntl(fd, F_SETLK, &lock);
+}
+/*
+ * Function RemoveMutex: remove a mutex (unlinking the lock file).
+ *
+ * Just remove the lock file.
+ *
+ * Input: a filename
+ * Output: a return code (0 OK, -1 KO)
+ */
+int RemoveMutex(const char *path_name)
+{
+ return unlink(path_name);
+}
+/*
+ * Function ReadMutex: read a mutex status.
+ *
+ * Read the status for a mutex.
+ *
+ * Input: a mutex (i.e. a file descriptor)
+ * Output: the lock type (F_UNLCK, F_RDLCK or F_WRLCK, or -1 if KO)
+ */
+int ReadMutex(int fd)
+{
+ int res;
+ struct flock lock; /* file lock structure */
+ /* set flock structure */
+ lock.l_type = F_WRLCK; /* set type: unlock */
+ lock.l_whence = SEEK_SET; /* start from the beginning of the file */
+ lock.l_start = 0; /* set the start of the locked region */
+ lock.l_len = 0; /* set the length of the locked region */
+ /* do locking */
+ if ( (res = fcntl(fd, F_GETLK, &lock)) ) {
+ return res;
+ }
+ return lock.l_type;
+}
--- /dev/null
+/* ProcInfo.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program test_fopen.c:
+ * Program to test function fopen
+ *
+ * Author: Simone Piccardi
+ * Dec. 2001
+ *
+ * Usage: procinfo -h give all info's
+ *
+ * $Id: ProcInfo.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#define _GNU_SOURCE
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i;
+ FILE * file;
+ char * ptr;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* There must be 2 remaing parameters */
+ if ( (argc-optind) != 2 ) {
+ printf("From %d arguments, removed %d options\n", argc, optind);
+ usage();
+ }
+ if ( !(file = fopen(argv[1], argv[2]))) {
+ perror("cannot open file");
+ exit(1);
+ }
+ i = 100;
+ ptr = malloc(i);
+ getline(&ptr, &i, file);
+// fclean(file); /* do not exist on Linux */
+ flockfile(file);
+ fclose(file);
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program testfopen : test fopen for a file \n");
+ printf("Usage:\n");
+ printf(" testfopen [-h] file mode \n");
+ printf(" -h print this help\n");
+
+ exit(1);
+}
+
--- /dev/null
+/* ReadMonitor.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File ReadMonitor:
+ *
+ * An example for shared memory use: read data saved in a shared
+ * memory segment from the DirMonitor program
+ *
+ * Author: S. Piccardi Jan. 2003
+ *
+ * $Id: ReadMonitor.c,v 1.5 2003/05/02 09:55:14 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h> /* directory */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h>
+
+#include "Gapil.h"
+#include "macros.h"
+
+/* Help printing routine */
+void usage(void);
+
+/* variables for shared memory segment */
+int shmid;
+struct DirProp {
+ int tot_size;
+ int tot_files;
+ int tot_regular;
+ int tot_fifo;
+ int tot_link;
+ int tot_dir;
+ int tot_block;
+ int tot_char;
+ int tot_sock;
+};
+struct DirProp *shmptr;
+int mutex;
+
+int main(int argc, char *argv[])
+{
+ int i;
+ key_t key;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hs:l:wrbf")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* create needed IPC objects */
+ key = ftok("~/gapil/sources/DirMonitor.c", 1); /* define a key */
+ if (!(shmptr = ShmFind(key, 4096))) { /* get a shared memory segment */
+ perror("Cannot find shared memory");
+ exit(1);
+ }
+ if ((mutex = MutexFind(key)) == -1) { /* get the Mutex */
+ perror("Cannot find mutex");
+ }
+ /* main loop */
+ MutexLock(mutex); /* lock shared memory */
+ printf("Ci sono %d file dati\n", shmptr->tot_regular);
+ printf("Ci sono %d directory\n", shmptr->tot_dir);
+ printf("Ci sono %d link\n", shmptr->tot_link);
+ printf("Ci sono %d fifo\n", shmptr->tot_fifo);
+ printf("Ci sono %d socket\n", shmptr->tot_sock);
+ printf("Ci sono %d device a caratteri\n", shmptr->tot_char);
+ printf("Ci sono %d device a blocchi\n", shmptr->tot_block);
+ printf("Totale %d file, per %d byte\n",
+ shmptr->tot_files, shmptr->tot_size);
+ MutexUnlock(mutex); /* unlock shared memory */
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program myls: list file in a directory \n");
+ printf("Usage:\n");
+ printf(" myls [-h] dirname \n");
+ printf(" -h print this help\n");
+ exit(1);
+}
--- /dev/null
+/* SetTermAttr.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine SetTermAttr
+ * Routine to set a local attribute for a terminal
+ *
+ * Author: Simone Piccardi
+ * Jun. 2001
+ *
+ * $Id: SetTermAttr.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+#include <unistd.h>
+#include <termios.h>
+#include <errno.h>
+
+int SetTermAttr(int fd, tcflag_t flag)
+{
+ struct termios values;
+ int res;
+
+ res = tcgetattr (desc, &values);
+ if (res) {
+ perror("Cannot get attributes");
+ return res;
+ }
+ values.c_lflag |= flag;
+ res = tcsetattr (desc, TCSANOW, &values);
+ if (res) {
+ perror("Cannot set attributes");
+ return res;
+ }
+ return 0;
+}
+int UnSetTermAttr(int fd, tcflag_t flag)
+{
+ struct termios values;
+ int res;
+
+ res = tcgetattr (desc, &values);
+ if (res) {
+ perror("Cannot get attributes");
+ return res;
+ }
+ values.c_lflag &= (~flag);
+ res = tcsetattr (desc, TCSANOW, &values);
+ if (res) {
+ perror("Cannot set attributes");
+ return res;
+ }
+ return 0;
+}
+
--- /dev/null
+/* SharedMem.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/***************************************************************
+ *
+ * File SharedMem.c
+ * Routines for Shared Memory use.
+ *
+ * Define two interfaces, the first one use SysV shared memory, the
+ * second POSIX shared memory.
+ *
+ * Author: S. Piccardi
+ *
+ * $Id: SharedMem.c,v 1.8 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ***************************************************************/
+#include <sys/shm.h> /* SysV IPC shared memory declarations */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h> /* standard I/O functions */
+#include <fcntl.h>
+#include <signal.h> /* signal handling declarations */
+#include <unistd.h>
+#include <sys/mman.h>
+#include <string.h>
+#include <errno.h>
+
+#include "macros.h"
+/* *************************************************************************
+ *
+ * Functions for SysV shared memory
+ *
+ * ************************************************************************* */
+/*
+ * Function ShmCreate:
+ * Create and attach a SysV shared memory segment to the current process.
+ *
+ * First call get a shared memory segment with KEY key access and size SIZE,
+ * by creating it with R/W privilege for the user (this is the meaning of
+ * the ored flags). The function return an identifier shmid used for any
+ * further reference to the shared memory segment.
+ * Second call attach the shared memory segment to this process and return a
+ * pointer to it (of void * type).
+ * Then initialize shared memory to the given value
+ *
+ * Input: an IPC key value
+ * the shared memory segment size
+ * the permissions
+ * the fill value
+ * Return: the address of the shared memory segment (NULL on error)
+ */
+void * ShmCreate(key_t ipc_key, int shm_size, int perm, int fill)
+{
+ void * shm_ptr;
+ int shm_id; /* ID of the IPC shared memory segment */
+ shm_id = shmget(ipc_key, shm_size, IPC_CREAT|perm); /* get shm ID */
+ if (shm_id < 0) {
+ return NULL;
+ }
+ shm_ptr = shmat(shm_id, NULL, 0); /* map it into memory */
+ if (shm_ptr < 0) {
+ return NULL;
+ }
+ memset((void *)shm_ptr, fill, shm_size); /* fill segment */
+ return shm_ptr;
+}
+/*
+ * Function ShmFind:
+ * Find a SysV shared memory segment
+ * Input: an IPC key value
+ * the shared memory segment size
+ * Return: the address of the segment (NULL on error)
+ */
+void * ShmFind(key_t ipc_key, int shm_size)
+{
+ void * shm_ptr;
+ int shm_id; /* ID of the SysV shared memory segment */
+ shm_id = shmget(ipc_key, shm_size, 0); /* find shared memory ID */
+ if (shm_id < 0) {
+ return NULL;
+ }
+ shm_ptr = shmat(shm_id, NULL, 0); /* map it into memory */
+ if (shm_ptr < 0) {
+ return NULL;
+ }
+ return shm_ptr;
+}
+/*
+ * Function ShmRemove:
+ * Schedule removal for a SysV shared memory segment
+ * Input: an IPC key value
+ * the shared memory segment size
+ * Return: 0 on success, -1 on error
+ */
+int ShmRemove(key_t ipc_key, void * shm_ptr)
+{
+ int shm_id; /* ID of the SysV shared memory segment */
+ /* first detach segment */
+ if (shmdt(shm_ptr) < 0) {
+ return -1;
+ }
+ /* schedule segment removal */
+ shm_id = shmget(ipc_key, 0, 0); /* find shared memory ID */
+ if (shm_id < 0) {
+ if (errno == EIDRM) return 0;
+ return -1;
+ }
+ if (shmctl(shm_id, IPC_RMID, NULL) < 0) { /* ask for removal */
+ if (errno == EIDRM) return 0;
+ return -1;
+ }
+ return 0;
+}
+/* *************************************************************************
+ *
+ * Functions for POSIX shared memory
+ *
+ * ************************************************************************* */
+/*
+ * Function CreateShm:
+ * Create a POSIX shared memory segment and map it to the current process.
+ *
+ *
+ * Input: a pathname
+ * the shared memory segment size
+ * the permissions
+ * the fill value
+ * Return: the address of the shared memory segment (NULL on error)
+ */
+void * CreateShm(char * shm_name, off_t shm_size, mode_t perm, int fill)
+{
+ void * shm_ptr;
+ int fd;
+ int flag;
+ /* first open the object, creating it if not existent */
+ flag = O_CREAT|O_EXCL|O_RDWR;
+ fd = shm_open(shm_name, flag, perm); /* get object file descriptor */
+ if (fd < 0) {
+ perror("errore in shm_open");
+ return NULL;
+ }
+ /* set the object size */
+ if (ftruncate(fd, shm_size)) {
+ perror("errore in ftruncate");
+ return NULL;
+ }
+ /* map it in the process address space */
+ shm_ptr = mmap(NULL, shm_size, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
+ if (shm_ptr == MAP_FAILED) {
+ perror("errore in mmap");
+ return NULL;
+ }
+ memset((void *) shm_ptr, fill, shm_size); /* fill segment */
+ return shm_ptr;
+}
+/*
+ * Function FindShm:
+ * Find a POSIX shared memory segment
+ * Input: a name
+ * the shared memory segment size
+ * Return: the address of the segment (NULL on error)
+ */
+void * FindShm(char * shm_name, off_t shm_size)
+{
+ void * shm_ptr;
+ int fd; /* ID of the IPC shared memory segment */
+ /* find shared memory ID */
+ if ((fd = shm_open(shm_name, O_RDWR|O_EXCL, 0)) < 0) {
+ debug("Cannot open %s\n", shm_name);
+ return NULL;
+ }
+ /* take the pointer to it */
+ shm_ptr = mmap(NULL, shm_size, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
+ if (shm_ptr == MAP_FAILED) {
+ return NULL;
+ }
+ return shm_ptr;
+}
+/*
+ * Function RemoveShm:
+ * Remove a POSIX shared memory segment
+ * Input: the object name
+ * Return: 0 on success, -1 on error
+ */
+int RemoveShm(char * shm_name)
+{
+ return shm_unlink(shm_name);
+}
--- /dev/null
+/* SigHand.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File SigHand.c: define a set of functions for signal manipulation
+ *
+ * Author: S. Piccardi Dec. 2002
+ *
+ * $Id: SigHand.c,v 1.5 2003/05/02 09:55:14 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <errno.h> /* error simbol definitions */
+#include <stdio.h> /* standard I/O functions */
+#include <signal.h> /* signal handling declarations */
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include "Gapil.h"
+#include "macros.h"
+
+/*
+ * Function Signal
+ * Initialize a signal handler.
+ * To enable the signal handling a process we need to tell it to
+ * kernel; this is done writing all needed info to a sigaction structure
+ * named sigact, and then callind sigaction() system call passing the
+ * information stored in the sigact structure variable.
+ *
+ * Input: the signal to handle
+ * the signal handler function
+ * Return: the previous sigaction structure
+ */
+inline SigFunc * Signal(int signo, SigFunc *func)
+{
+ struct sigaction new_handl, old_handl;
+ new_handl.sa_handler = func; /* set signal handler */
+ /* clear signal mask: no signal blocked during execution of func */
+ if (sigemptyset(&new_handl.sa_mask)!=0){ /* initialize signal set */
+ return SIG_ERR;
+ }
+ new_handl.sa_flags=0; /* init to 0 all flags */
+ /* change action for signo signal */
+ if (sigaction(signo,&new_handl,&old_handl)){
+ return SIG_ERR;
+ }
+ return (old_handl.sa_handler);
+}
+/*
+ * Functions: HandSigCHLD
+ * Generic handler for SIGCHLD signal
+ *
+ * Simone Piccardi Dec. 2002
+ * $Id: SigHand.c,v 1.5 2003/05/02 09:55:14 piccardi Exp $
+ */
+void HandSigCHLD(int sig)
+{
+ int errno_save;
+ int status;
+ pid_t pid;
+ /* save errno current value */
+ errno_save = errno;
+ /* loop until no */
+ do {
+ errno = 0;
+ pid = waitpid(WAIT_ANY, &status, WNOHANG);
+ if (pid > 0) {
+ debug("child %d terminated with status %x\n", pid, status);
+ }
+ } while ((pid > 0) && (errno == EINTR));
+ /* restore errno value*/
+ errno = errno_save;
+ /* return */
+ return;
+}
--- /dev/null
+/* Sleep.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program Sleep.c:
+ * Example implementation for sleep
+ *
+ * Author: Simone Piccardi
+ * Apr. 2002
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <unistd.h> /* unix standard library */
+#include <signal.h> /* POSIX signal library */
+
+void alarm_hand(int);
+
+unsigned int sleep(unsigned int seconds)
+{
+/*
+ * Variables definition
+ */
+ struct sigaction new_action, old_action;
+ sigset_t old_mask, stop_mask, sleep_mask;
+ /* set the signal handler */
+ sigemptyset(&new_action.sa_mask); /* no signal blocked */
+ new_action.sa_handler = alarm_hand; /* set handler */
+ new_action.sa_flags = 0; /* no flags */
+ sigaction(SIGALRM, &new_action, &old_action); /* install action */
+ /* block SIGALRM to avoid race conditions */
+ sigemptyset(&stop_mask); /* init mask to empty */
+ sigaddset(&stop_mask, SIGALRM); /* add SIGALRM */
+ sigprocmask(SIG_BLOCK, &stop_mask, &old_mask); /* add SIGALRM to blocked */
+ /* send the alarm */
+ alarm(seconds);
+ /* going to sleep enabling SIGALRM */
+ sleep_mask = old_mask; /* take mask */
+ sigdelset(&sleep_mask, SIGALRM); /* remove SIGALRM */
+ sigsuspend(&sleep_mask); /* go to sleep */
+ /* restore previous settings */
+ sigprocmask(SIG_SETMASK, &old_mask, NULL); /* reset signal mask */
+ sigaction(SIGALRM, &old_action, NULL); /* reset signal action */
+ /* return remaining time */
+ return alarm(0);
+}
+/*
+ * Signal Handler for SIGALRM
+ */
+void alarm_hand(int sig) {
+ /* just return to interrupt sigsuspend */
+ return;
+}
--- /dev/null
+/* TCP_cunc_daytimed.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program TCP_cunc_daytimed.c
+ * Elementary TCP cuncurrent server for daytime service (port 13)
+ *
+ * Author: Simone Piccardi
+ * May. 2001
+ *
+ * Usage: daytimed -h give all info
+ *
+ * $Id: TCP_cunc_daytimed.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <unistd.h> /* include unix standard library */
+#include <arpa/inet.h> /* IP addresses conversion utiliites */
+#include <sys/socket.h> /* socket library */
+#include <stdio.h> /* include standard I/O library */
+#include <time.h>
+
+#define MAXLINE 80
+#define BACKLOG 10
+/* Program begin */
+void usage(void);
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int list_fd, conn_fd;
+ int i;
+ struct sockaddr_in serv_add, client;
+ char buffer[MAXLINE];
+ socklen_t len;
+ time_t timeval;
+ pid_t pid;
+ int logging=0;
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hv")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ return(0);
+ break;
+ case 'v':
+ logging = 1;
+ break;
+ default: /* should not reached */
+ usage();
+ return(0);
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* create socket */
+ if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("Socket creation error");
+ exit(-1);
+ }
+ /* initialize address */
+ memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
+ serv_add.sin_family = AF_INET; /* address type is INET */
+ serv_add.sin_port = htons(13); /* daytime port is 13 */
+ serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
+ /* bind socket */
+ if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
+ perror("bind error");
+ exit(-1);
+ }
+ /* listen on socket */
+ if (listen(list_fd, BACKLOG) < 0 ) {
+ perror("listen error");
+ exit(-1);
+ }
+ /* write daytime to client */
+ while (1) {
+ if ( (conn_fd = accept(list_fd, (struct sockaddr *)&client, &len))
+ <0 ) {
+ perror("accept error");
+ exit(-1);
+ }
+ /* fork to handle connection */
+ if ( (pid = fork()) < 0 ){
+ perror("fork error");
+ exit(-1);
+ }
+ if (pid == 0) { /* child */
+ close(list_fd);
+ timeval = time(NULL);
+ snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
+ if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
+ perror("write error");
+ exit(-1);
+ }
+ if (logging) {
+ inet_ntop(AF_INET, &client.sin_addr, buffer, sizeof(buffer));
+ printf("Request from host %s, port %d\n", buffer,
+ ntohs(client.sin_port));
+ }
+ close(conn_fd);
+ exit(0);
+ } else { /* parent */
+ close(conn_fd);
+ }
+ }
+ /* normal exit, never reached */
+ exit(0);
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Simple daytime server\n");
+ printf("Usage:\n");
+ printf(" daytimed [-hv] \n");
+ printf(" -h print this help\n");
+ printf(" -v print request source on stdout\n");
+ exit(1);
+}
+
--- /dev/null
+/* TCP_daytime.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program daytime:
+ * Elementary TCP client for daytime service (port 13)
+ *
+ * Author: Simone Piccardi
+ * Apr. 2001
+ *
+ * Usage: daytime -h give all info's
+ *
+ * $Id: TCP_daytime.c,v 1.4 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <unistd.h> /* include unix standard library */
+#include <arpa/inet.h> /* IP addresses conversion utiliites */
+#include <sys/socket.h> /* socket library */
+#include <stdio.h> /* include standard I/O library */
+
+#define MAXLINE 80
+/* Program begin */
+void usage(void);
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int sock_fd;
+ int i, nread;
+ struct sockaddr_in serv_add;
+ char buffer[MAXLINE];
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* create socket */
+ if ( (sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("Socket creation error");
+ return -1;
+ }
+ /* initialize address */
+ memset((void *) &serv_add, 0, sizeof(serv_add)); /* clear server address */
+ serv_add.sin_family = AF_INET; /* address type is INET */
+ serv_add.sin_port = htons(13); /* daytime port is 13 */
+ /* build address using inet_pton */
+ if ( (inet_pton(AF_INET, argv[optind], &serv_add.sin_addr)) <= 0) {
+ perror("Address creation error");
+ return -1;
+ }
+ /* extablish connection */
+ if (connect(sock_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
+ perror("Connection error");
+ return -1;
+ }
+ /* read daytime from server */
+ while ( (nread = read(sock_fd, buffer, MAXLINE)) > 0) {
+ buffer[nread]=0;
+ if (fputs(buffer, stdout) == EOF) { /* write daytime */
+ perror("fputs error");
+ return -1;
+ }
+ }
+ /* error on read */
+ if (nread < 0) {
+ perror("Read error");
+ return -1;
+ }
+ /* normal exit */
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Take daytime from a remote host \n");
+ printf("Usage:\n");
+ printf(" daytime [-h] [-v] [host in dotted decimal form] \n");
+ printf(" -v set verbosity on\n");
+ printf(" -h print this help\n");
+ exit(1);
+}
--- /dev/null
+/* TCP_iter_daytimed.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program daytimed:
+ * Elementary TCP server for daytime service (port 13)
+ *
+ * Author: Simone Piccardi
+ * Apr. 2001
+ *
+ * Usage: daytimed -h give all info
+ *
+ * $Id: TCP_iter_daytimed.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <sys/types.h> /* predefined types */
+#include <unistd.h> /* include unix standard library */
+#include <arpa/inet.h> /* IP addresses conversion utiliites */
+#include <sys/socket.h> /* socket library */
+#include <stdio.h> /* include standard I/O library */
+#include <time.h>
+
+#define MAXLINE 80
+#define BACKLOG 10
+/* Program begin */
+void usage(void);
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int list_fd, conn_fd;
+ int i;
+ struct sockaddr_in serv_add;
+ char buffer[MAXLINE];
+ time_t timeval;
+ /*
+ * Input section: decode parameters passed in the calling
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h':
+ printf("Wrong -h option use\n");
+ usage();
+ return(0);
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* create socket */
+ if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("Socket creation error");
+ exit(-1);
+ }
+ /* initialize address */
+ memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
+ serv_add.sin_family = AF_INET; /* address type is INET */
+ serv_add.sin_port = htons(13); /* daytime port is 13 */
+ serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
+ /* bind socket */
+ if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
+ perror("bind error");
+ exit(-1);
+ }
+ /* listen on socket */
+ if (listen(list_fd, BACKLOG) < 0 ) {
+ perror("listen error");
+ exit(-1);
+ }
+ /* write daytime to client */
+ while (1) {
+ if ( (conn_fd = accept(list_fd, (struct sockaddr *) NULL, NULL)) <0 ) {
+ perror("accept error");
+ exit(-1);
+ }
+ timeval = time(NULL);
+ snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
+ if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
+ perror("write error");
+ exit(-1);
+ }
+ close(conn_fd);
+ }
+
+ /* normal exit */
+ exit(0);
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Simple daytime server\n");
+ printf("Usage:\n");
+ printf(" daytimed [-h] \n");
+ printf(" -h print this help\n");
+ exit(1);
+}
--- /dev/null
+/* TestRen.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program TestRen.c:
+ * Program to test function rename
+ *
+ * Author: Simone Piccardi
+ * Oct. 2001
+ *
+ * Usage: testrem -h give all info's
+ *
+ * $Id: TestRen.c,v 1.4 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i;
+ char *buf,*copy;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ buf = malloc(100);
+
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* There must be 2 remaing parameters */
+ if ( (argc-optind) != 2 ) {
+ printf("From %d arguments, removed %d options\n", argc, optind);
+ usage();
+ }
+ if ( rename(argv[optind], argv[optind+1]) ) {
+ copy = strerror_r(errno, NULL, 0);
+ perror("cannot rename");
+ exit(1);
+ }
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program testren : test renaming of file/directories \n");
+ printf("Usage:\n");
+ printf(" testrem [-h] fileorig filedest \n");
+ printf(" -h print this help\n");
+
+ exit(1);
+}
+
--- /dev/null
+/* WriteShm.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File WriteShm.c:
+ *
+ * An example of POSIX shared memory use: wwrite some content to a
+ * shared memory segment
+ *
+ * Author: S. Piccardi Jan. 2003
+ *
+ * $Id: WriteShm.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h> /* directory */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h>
+#include <stdio.h>
+
+#include "Gapil.h"
+#include "macros.h"
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+ int i;
+ int size = 4096;
+ char * file_name = NULL;
+ int fd = 0;
+ int mutex;
+ char * mutex_file;
+ void * shm_ptr;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hs:f:")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 's': /* set pause (in sec.) */
+ size = strtol(optarg, NULL, 10);
+ break;
+ case 'f': /* set pause (in sec.) */
+ file_name = optarg;
+ break;
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if ((argc - optind) != 1) { /* There must be remaing parameters */
+ printf("Wrong number of arguments %d\n", argc - optind);
+ usage();
+ }
+ mutex_file = tempnam("/tmp","mutex");
+ if ((mutex = CreateMutex(mutex_file)) == -1) { /* get a Mutex */
+ perror("Cannot create mutex");
+ goto errmutex;
+ }
+ /* main loop */
+ shm_ptr = CreateShm(argv[1], size, 0644, 0);
+ if (shm_ptr == NULL) {
+ perror("Error creating shared memory");
+ goto errshared;
+ }
+ if (file_name) {
+ fd = open(file_name, O_RDONLY);
+ }
+ FullRead(fd, shm_ptr, size);
+// RemoveShm(argv[1]);
+ RemoveMutex(mutex_file);
+ exit(0);
+ errshared:
+ RemoveShm(argv[1]);
+ RemoveMutex(mutex_file);
+ errmutex:
+ exit(1);
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program myls: list file in a directory \n");
+ printf("Usage:\n");
+ printf(" WriteShm [-h] [-s size] [-f file] name \n");
+ printf(" -h print this help\n");
+ printf(" -s size size of segment \n");
+ printf(" -f file filename to read contents \n");
+ exit(1);
+}
--- /dev/null
+/* gethost.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program gethost.c:
+ * Program to test gethostbyname and getaddrinfo
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: gethost -h give all info's
+ *
+ * $Id: gethost.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#define _GNU_SOURCE
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netdb.h>
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i;
+ int use = 0;
+ struct hostent *host;
+ struct in_addr addr;
+ struct addrinfo hint;
+ struct addrinfo *address;
+ struct sockaddr_in *socket;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "han")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case 'a': /* help option */
+ use = 1;
+ break;
+ case 'n': /* help option */
+ use = 0;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if ((argc-optind)!= 1) {
+ printf("From %d arguments, removed %d options\n", argc, optind);
+ usage();
+ }
+ if (use == 0) {
+ host = gethostbyname(argv[optind]);
+ printf("gethostbyname %s\n", argv[optind]);
+ printf("Official host name %s\n", host->h_name);
+ printf("Address Type %d\n", host->h_addrtype);
+ printf("Address Lenght %d\n", host->h_length);
+ addr.s_addr = *( (unsigned long *)host->h_addr);
+ printf("Address %s\n", inet_ntoa(addr));
+ } else {
+/* host = getipnodebyname(argv[optind], AF_INET, 0, &i); */
+/* if (!host) printf("Error\n"); */
+/* printf("getipnodebyname %s, error %d\n", argv[optind], i); */
+/* printf("Official host name %s\n", host->h_name); */
+/* printf("Address Type %d\n", host->h_addrtype); */
+/* printf("Address Lenght %d\n", host->h_length); */
+/* addr.s_addr = *( (unsigned long *)host->h_addr); */
+/* printf("Address %s\n", inet_ntoa(addr)); */
+ hint.ai_flags = 0;
+ hint.ai_family = PF_INET;
+ hint.ai_socktype = 0;
+ hint.ai_protocol = 0;
+ hint.ai_addrlen = 0;
+ hint.ai_addr = NULL;
+ hint.ai_canonname = NULL;
+ hint.ai_next = NULL;
+ if (i = getaddrinfo(argv[optind], "telnet", &hint, &address)) {
+ printf("getaddrinfo %s = %s \n", argv[optind], gai_strerror(i));
+ } else {
+ printf("Address flag %d\n", address->ai_flags);
+ printf("Address family %d\n", address->ai_family);
+ printf("Address socket type %d\n", address->ai_socktype);
+ printf("Address protocol %d\n", address->ai_protocol);
+ printf("Address lenght %d\n", address->ai_addrlen);
+ printf("Canonical name %s\n", address->ai_canonname);
+ socket = (struct sockaddr_in *) address->ai_addr;
+ printf("Address %s\n", inet_ntoa(socket->sin_addr));
+ printf("Port %d\n", htons(socket->sin_port));
+ printf("Family %d\n", socket->sin_family);
+
+ }
+ }
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program gehost: test host name functions \n");
+ printf("Usage:\n");
+ printf(" gethost [-h] address \n");
+ printf(" -h print this help\n");
+ printf(" -a use getaddrinfo\n");
+ printf(" -n use gethostbyname\n");
+
+ exit(1);
+}
+
--- /dev/null
+/* getparam.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program getparam.c:
+ * Program to test function fopen
+ *
+ * Author: Simone Piccardi
+ * Jan. 2002
+ *
+ * Usage: getparam -h give all info's
+ *
+ * $Id: getparam.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#define _GNU_SOURCE
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <string.h> /* string functions */
+#include <limits.h>
+#include <stdio.h>
+
+
+#include <time.h> /* for CLK_TCK e CLOCKS_PER_SEC */
+
+/* Table of constants for sysconf() */
+char *sc_names[]={"_SC_ARG_MAX",
+ "_SC_CHILD_MAX",
+ "_SC_OPEN_MAX",
+ "_SC_STREAM_MAX",
+ "_SC_TZNAME_MAX",
+ "_SC_NGROUPS_MAX",
+ "_SC_SSIZE_MAX",
+ "_SC_CLK_TCK",
+ "_SC_JOB_CONTROL",
+ "_SC_SAVED_IDS",
+ "_SC_VERSION"};
+
+int sc_argument[]={_SC_ARG_MAX,
+ _SC_CHILD_MAX,
+ _SC_OPEN_MAX,
+ _SC_STREAM_MAX,
+ _SC_TZNAME_MAX,
+ _SC_NGROUPS_MAX,
+ _SC_SSIZE_MAX,
+ _SC_CLK_TCK,
+ _SC_JOB_CONTROL,
+ _SC_SAVED_IDS,
+ _SC_VERSION};
+
+/*
+ Set the defined[] array to true if the macro is defined else set it
+ to false and define the macro to -1 as a marker
+*/
+int defined[]={
+#ifdef ARG_MAX
+ 1,
+#else
+#define ARG_MAX -1
+ 0,
+#endif
+#ifdef CHILD_MAX
+ 1,
+#else
+#define CHILD_MAX -1
+ 0,
+#endif
+#ifdef OPEN_MAX
+ 1,
+#else
+#define OPEN_MAX -1
+ 0,
+#endif
+#ifdef STREAM_MAX
+ 1,
+#else
+#define STREAM_MAX -1
+ 0,
+#endif
+#ifdef NGROUPS_MAX
+ 1,
+#else
+#define NGROUPS_MAX -1
+ 0,
+#endif
+#ifdef TZNAME_MAX
+ 1,
+#else
+#define TZNAME_MAX -1
+ 0,
+#endif
+#ifdef SSIZE_MAX
+ 1
+#else
+#define SSIZE_MAX -1
+ 0
+};
+
+
+
+/* values of stadard macros */
+long values[]={ARG_MAX,
+ CHILD_MAX,
+ OPEN_MAX,
+ STREAM_MAX,
+ TZNAME_MAX,
+ NGROUPS_MAX,
+ SSIZE_MAX,
+ CLOCKS_PER_SEC,
+ _POSIX_JOB_CONTROL,
+ _POSIX_SAVED_IDS,
+ _POSIX_VERSION};
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* There must be 2 remaing parameters */
+ if ( (argc-optind) != 1 ) {
+ printf("From %d arguments, removed %d options\n", argc, optind);
+ usage();
+ }
+ for (i=0; i<=4; i++) {
+ printf("Response for %s is %ld, values is %ld\n", names[i],
+ sysconf(argument[i]), values[i]);
+ }
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program testfopen : test fopen for a file \n");
+ printf("Usage:\n");
+ printf(" testfopen [-h] file mode \n");
+ printf(" -h print this help\n");
+
+ exit(1);
+}
+
--- /dev/null
+/* myls.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/*****************************************************************************
+ *
+ * File myls.c: An example ls
+ *
+ * Author: S. Piccardi Jan. 2003
+ *
+ * $Id: myls.c,v 1.4 2003/05/02 09:55:14 piccardi Exp $
+ *
+ *****************************************************************************/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h> /* directory */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h>
+
+#include "Gapil.h"
+/*
+ * Program myls
+ *
+ * List files and their size inside a given directory
+ */
+/* Help printing routine */
+void usage(void);
+/* computation function for DirScan */
+int do_ls(struct dirent * direntry);
+
+int main(int argc, char *argv[])
+{
+ int i;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "hs:l:wrbf")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ if ((argc - optind) != 1) { /* There must be remaing parameters */
+ printf("Wrong number of arguments %d\n", argc - optind);
+ usage();
+ }
+ DirScan(argv[1], do_ls);
+ exit(0);
+}
+/*
+ * Routine to print file name and size inside DirScan
+ */
+int do_ls(struct dirent * direntry)
+{
+ struct stat data;
+ stat(direntry->d_name, &data); /* get stat data */
+ printf("File: %s \t size: %d\n", direntry->d_name, data.st_size);
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program myls: list file in a directory \n");
+ printf("Usage:\n");
+ printf(" myls [-h] dirname \n");
+ printf(" -h print this help\n");
+ exit(1);
+}
--- /dev/null
+/* sleep1.c
+ *
+ * Copyright (C) 2002 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program sleep1.c:
+ * Example of a broken implementation for sleep
+ *
+ * Author: Simone Piccardi
+ * Mar. 2002
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#define _GNU_SOURCE
+#include <unistd.h> /* unix standard library */
+#include <signal.h> /* signal standard library */
+
+void alarm_hand(int sig) {
+ /* check if the signal is the right one */
+ if (sig != SIGALRM) { /* if not exit with error */
+ printf("Something wrong, handler for SIGALRM\n");
+ exit(1);
+ } else { /* do nothing, just interrupt pause */
+ return;
+ }
+}
+unsigned int sleep(unsigned int seconds)
+{
+ sighandler_t prev_handler;
+ /* install and check new handler */
+ if ((prev_handler = signal(SIGALRM, alarm_hand)) == SIG_ERR) {
+ printf("Cannot set handler for alarm\n");
+ exit(-1);
+ }
+ /* set alarm and go to sleep */
+ alarm(seconds);
+ pause();
+ /* restore previous signal handler */
+ signal(SIGALRM, prev_handler);
+ /* return remaining time */
+ return alarm(0);
+}
--- /dev/null
+/* test_fopen.c
+ *
+ * Copyright (C) 2001 Simone Piccardi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Program test_fopen.c:
+ * Program to test function fopen
+ *
+ * Author: Simone Piccardi
+ * Oct. 2001
+ *
+ * Usage: testfopen -h give all info's
+ *
+ * $Id: test_fopen.c,v 1.3 2003/05/02 09:55:14 piccardi Exp $
+ *
+ ****************************************************************/
+/*
+ * Include needed headers
+ */
+#define _GNU_SOURCE
+#include <errno.h> /* error definitions and routines */
+#include <stdlib.h> /* C standard library */
+#include <unistd.h> /* unix standard library */
+#include <stdio.h> /* standard I/O library */
+#include <string.h> /* string functions */
+
+/* Help printing routine */
+void usage(void);
+
+int main(int argc, char *argv[])
+{
+/*
+ * Variables definition
+ */
+ int i;
+ FILE * file;
+ char * ptr;
+ /*
+ * Input section: decode command line parameters
+ * Use getopt function
+ */
+ opterr = 0; /* don't want writing to stderr */
+ while ( (i = getopt(argc, argv, "h")) != -1) {
+ switch (i) {
+ /*
+ * Handling options
+ */
+ case 'h': /* help option */
+ printf("Wrong -h option use\n");
+ usage();
+ return -1;
+ break;
+ case '?': /* unrecognized options */
+ printf("Unrecognized options -%c\n",optopt);
+ usage();
+ default: /* should not reached */
+ usage();
+ }
+ }
+ /* ***********************************************************
+ *
+ * Options processing completed
+ *
+ * Main code beginning
+ *
+ * ***********************************************************/
+ /* There must be 2 remaing parameters */
+ if ( (argc-optind) != 2 ) {
+ printf("From %d arguments, removed %d options\n", argc, optind);
+ usage();
+ }
+ if ( !(file = fopen(argv[1], argv[2]))) {
+ perror("cannot open file");
+ exit(1);
+ }
+ i = 100;
+ ptr = malloc(i);
+ getline(&ptr, &i, file);
+// fclean(file); /* do not exist on Linux */
+ flockfile(file);
+ fclose(file);
+ return 0;
+}
+/*
+ * routine to print usage info and exit
+ */
+void usage(void) {
+ printf("Program testfopen : test fopen for a file \n");
+ printf("Usage:\n");
+ printf(" testfopen [-h] file mode \n");
+ printf(" -h print this help\n");
+
+ exit(1);
+}
+