ProvaPratica 2011.05.30
Jump to navigation
Jump to search
Esercizio 1
sender.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#define COMMUNICATION_SIGNAL 25
#define MAXIMUM_LENGTH 4096
#define PID_LENGTH 10
int main(int argc,char *argv[])
{
int sharedFD = shm_open("/sharedPID", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(!sharedFD)
return;
ftruncate(sharedFD,sizeof(char)*PID_LENGTH);
char *sharedVariable = mmap(NULL,sizeof(char)*PID_LENGTH,PROT_READ | PROT_WRITE,MAP_SHARED,sharedFD,0);
int effectivePID = atoi(sharedVariable);
int sharedParametersFD = shm_open("/sharedParameters", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(!sharedParametersFD)
return;
ftruncate(sharedParametersFD,sizeof(char)*MAXIMUM_LENGTH);
char *parameters = mmap(NULL,sizeof(char)*MAXIMUM_LENGTH,PROT_READ | PROT_WRITE,MAP_SHARED,sharedParametersFD,0);
char parametersToPass[MAXIMUM_LENGTH];
int i;
for(i=0;i<MAXIMUM_LENGTH;i++)
parametersToPass[i]='\0';
for(i=0;i<argc;i++)
{
strcat(parametersToPass,argv[i]);
strcat(parametersToPass,"\n");
}
strcpy(parameters,parametersToPass);
kill(effectivePID,COMMUNICATION_SIGNAL);
return 0;
}
receiver.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#define COMMUNICATION_SIGNAL 25
#define MAXIMUM_LENGTH 4096
#define PID_LENGTH 10
static void signalHandler (int sig, siginfo_t *siginfo, void *context)
{
int sharedFD = shm_open("/sharedParameters", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(!sharedFD)
return;
ftruncate(sharedFD,sizeof(char)*MAXIMUM_LENGTH);
char *parameters = mmap(NULL,sizeof(char)*MAXIMUM_LENGTH,PROT_READ | PROT_WRITE,MAP_SHARED,sharedFD,0);
printf("Parameters: %s",parameters);
exit(0);
}
int main(int argc,char *argv[])
{
int sharedFD = shm_open("/sharedPID", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(!sharedFD)
return;
char *currentPIDToPass;
asprintf(¤tPIDToPass,"%d",getpid());
ftruncate(sharedFD,sizeof(char)*PID_LENGTH);
char *sharedVariable = mmap(NULL,sizeof(char)*PID_LENGTH,PROT_READ | PROT_WRITE,MAP_SHARED,sharedFD,0);
strcpy(sharedVariable,currentPIDToPass);
struct sigaction signalStruct;
signalStruct.sa_sigaction = &signalHandler;
sigaction(COMMUNICATION_SIGNAL,&signalStruct,NULL);
while(1){}
return 0;
}