Received signal SIGSEGV, Segmentation fault. C progran for message POSIX communicationproblem with flushing input stream CWhat is a segmentation fault?Realloc is not resizing array of pointersAligned attribute in CProgram received signal SIGSEGV, Segmentation fault errorUnable to access Struct contents properlyprogram received signal sigsegv segmentation faultReceiving signal SIGSEGV segmentation faultprogram receive signal SIGSEGV segmentation fault“program received signal SIGSEGV, Segmentation fault” in C

Is this toilet slogan correct usage of the English language?

Quoting Keynes in a lecture

15% tax on $7.5k earnings. Is that right?

Make a Bowl of Alphabet Soup

What kind of floor tile is this?

C++ check if statement can be evaluated constexpr

Review your own paper in Mathematics

What's the name of the logical fallacy where a debater extends a statement far beyond the original statement to make it true?

What is the English pronunciation of "pain au chocolat"?

Short story about a deaf man, who cuts people tongues

How would you translate "more" for use as an interface button?

Delete multiple columns using awk or sed

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Giving feedback to someone without sounding prejudiced

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

Which Article Helped Get Rid of Technobabble in RPGs?

What (the heck) is a Super Worm Equinox Moon?

What to do when eye contact makes your coworker uncomfortable?

How do I fix the group tension caused by my character stealing and possibly killing without provocation?

What features enable the Su-25 Frogfoot to operate with such a wide variety of fuels?

Why should universal income be universal?

Are Captain Marvel's powers affected by Thanos breaking the Tesseract and claiming the stone?

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?

Microchip documentation does not label CAN buss pins on micro controller pinout diagram



Received signal SIGSEGV, Segmentation fault. C progran for message POSIX communication


problem with flushing input stream CWhat is a segmentation fault?Realloc is not resizing array of pointersAligned attribute in CProgram received signal SIGSEGV, Segmentation fault errorUnable to access Struct contents properlyprogram received signal sigsegv segmentation faultReceiving signal SIGSEGV segmentation faultprogram receive signal SIGSEGV segmentation fault“program received signal SIGSEGV, Segmentation fault” in C













-1















Please take in mind that I don't want anyone to do my homework, but I have been almost three days unable to fix this problem and I don't feel I have the capacity to fix it soon. Here I go:



I am asked to do a POSIX communication system between several clients and a server. In order to do that I made the following code, every time a client send a request and the server receives it, the server makes a new thread that will manage the request.



Due to the problem I will try to explain now I have tried to redesign the hole code so now it is kind a mess.
The problem is that in any time after the server start a thread to handle the request I get a segmentation error.
Now I will post every piece of code required to reproduce the problem, and output example and the debug provided by gdb.



This is the client.c code



#include "libkeys.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>


void main()

char* key1="KEY1";
char* key2="KEY2";
char* key3="KEY3";
char* value11="VALUE11";
char* value12="VALUE12";
char* value13="VALUE13";
float value21=1.111;
float value22=2.222;
float value23=3.333;

float *p_value21=&value21;
float *p_value22=&value22;
float *p_value23=&value23;

printf("nCLIENT: Los valores se han seteado, va a proceder a ejecutarse initn");
init();

printf("nCLIENT: A partir de aqui no funciona ni de blasn");
/*set_value(key1, value11, value21);
set_value(key2, value12, value22);
set_value(key3, value13, value23);

printf("%dn",get_value( key1, value11, p_value21));
printf("VALUE1 %s n",value11);
printf("VALUE2 %f n",value21);

modify_value(key2, value13, p_value23);
printf("%dn",get_value( key2, value13, &value23));
printf("VALUE1 %s n",value13);
printf("VALUE2 %f n",value23);

printf("Num of items: %dn", num_items());
set_value(key3, value11, value23);
printf("Num of items: %dn", num_items());
delete_key(key1);
printf("Num of items: %dn", num_items());
exist(key1);
init();
exist(key1);
printf("Num of items: %dn", num_items());*/




Now, the library that client.c uses, called keys.c:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>

int NumberOfItems=0;



struct data
char value1[255];
float value2;
;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
printf("n CLIENT: Iniciamos int: n");
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=9;
attr.mq_msgsize=sizeof(int);

int client_pidINT=getpid();
char client_pidCHAR= (char) client_pidINT;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",client_pidINT);
//sprint saco el pid del cliente
printf("n CLIENT: Vamos a generar las colas");
q_client=mq_open(p_client_pidCHAR, O_CREAT

int set_value(char *key,char *value1, float value2)
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=1;
attr.mq_msgsize=sizeof(int);
//sprint saco el pid del cliente
q_client=mq_open("CLIENT_ONE", O_CREAT

int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
NumberOfItems--;
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

NumberOfItems--;


int num_items()
return NumberOfItems;



This is the library libkeys.h



#ifndef KEYAPI
#define KEYAPI

int init();

int set_value(char *key,char *value1, float value2);

int get_value(char *key, char *value1, float *value2);

int modify_value(char *key, char *value1, float *value2);

int exist(char *key);

int delete_key (char *key);

int num_items();

#endif


Finally this is the server.c code:



#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
/* mutex and condition variables for the message copy */
pthread_mutex_t mutex_msg;
int msg_not_copied = 1;
/* TRUE = 1 */
pthread_cond_t cond_msg;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;

//////////////////////////////////////////////////////////////////////FUNCIONES/////////////////////////////////////////////////////////////



int NumberOfItems=0;

pthread_mutex_t lock;






struct data
char value1[255];
float value2;
;



/**************************************************************************************************************************************************/
/****************************************************FUNCIONES*************************************************************************************/
/**************************************************************************************************************************************************/


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return -1;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);
/*if(rmdir(directory)==0)
printf("nSuccess removing the directoryn");
*/

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
return 0;


int set_value(char *key,char *value1, float value2)
FILE *ptr;
key=KeyForm(key);
printf("La clave creada es: %s",key);

if(ptr=fopen(key, "r"))
fclose(ptr);
printf("nEl archivo ya existen");
return -1;

printf("n El archivo no existia asi que se crea uno nuevo. n");
ptr=fopen(key, "w");
if (ptr ==NULL)
fprintf(stderr, "nError opend filen");
fclose(ptr);
exit (1);



char outputvalue1 [255];
int i;
for ( i = 0; i < 255; i++ )
outputvalue1[i]=*(value1 + i);


printf("El valor de la string es: %s", outputvalue1);

struct data input;
//input=value1,value2;
strcpy( input.value1, value1);
input.value2=value2;
printf("n string= %s n float= %f", input.value1, input.value2);
fwrite (&input,sizeof(struct data),1,ptr);

if(fwrite !=0) printf("n ha funcionado la escritura en el archvio n n");
else
printf ("se fue a la puta");
fclose (ptr);
return -1;

pthread_mutex_lock(&lock);
NumberOfItems++;
pthread_mutex_unlock(&lock);
fclose (ptr);
return 0;




int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);


int num_items()
pthread_mutex_lock(&lock);
return NumberOfItems;
pthread_mutex_unlock(&lock);



/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/





void process_message(struct mensaje *msg)
struct request msg_local; /* local message */
mqd_t q_client; /* client queue */

int result;

/* thread copies the message to local message*/
pthread_mutex_lock(&mutex_msg);
memcpy((char *) &msg_local, (char *)&msg, sizeof(struct request));

/* wake up server */
msg_not_copied = 0;
pthread_cond_signal(&cond_msg);
pthread_mutex_unlock(&mutex_msg);


char *p_key;
char *p_value1;
float *p_value2;

p_key=&msg_local.key;
p_value1=&msg_local.value1;
p_value2=&msg_local.value2;

/* execute client request and prepare reply */



result =0;

switch(msg_local.method)
//case 0 equivalent to init()
case 0:

int hola;
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
result =-1;
break;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
result=0;

break;


//case 1 equivalent to set_value
case 1: result=set_value(p_key, p_value1, msg_local.value2);break;


case 2: result=get_value(p_key, p_value1, p_value2);
break;

case 3: result=modify_value(p_key, p_value1, p_value2);
break;

case 4: result=delete_key(p_key);
break;

case 5: result=exist(p_key);
break;

case 6: result=num_items();
break;

default: printf("There was an error");
break;



// return result to client by sending it to queue
printf("ESTOY AQUIIIIIII Y EL RESULTADO ES: %d", result);
char client_pidCHAR= (char) msg_local.name;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",msg_local.name);
q_client = mq_open(client_pidCHAR, O_WRONLY); //msg_local.name es el nombre del cliente
// */
if (q_client == -1)
perror("Can't open client queue");
else
mq_send(q_client, (char *) &result, sizeof(int), 0);
mq_close(q_client);

pthread_exit(0);


///////////////////////////////MAIN/////////////////////
int main(void)O_RDONLY, 0700, &q_attr);

if (q_server == -1)
perror("Cant create server queue");
return 1;
else
printf(" n Server queue created succesgully n");


pthread_mutex_init(&mutex_msg, NULL);
pthread_cond_init(&cond_msg, NULL); //Iniziate the condition variable
pthread_attr_init(&t_attr);
/* thread atributes */
pthread_attr_setdetachstate(&t_attr, PTHREAD_CREATE_DETACHED);


for(;;)
printf("nSERVER %d: En 6s empiezo a buscar mensajes...n", getpid());
sleep(6);
printf("nSERVER %d: buscando mensajes...n", getpid());
if(mq_receive(q_server, &msg, sizeof(struct request), 0)==-1) //Poner en vez de 0 NULL al final?
printf("nSERVER %d: Error al recibir mensaje n", getpid());
else
printf("n SERVER %d: mensaje recibidon", getpid());

pthread_create(&thid, &t_attr, process_message, &msg);
sleep(6);
printf("nSERVER %d: copying the messagen", getpid());
/* wait for thread to copy message */
pthread_mutex_lock(&mutex_msg);
while (msg_not_copied)
pthread_cond_wait(&cond_msg, &mutex_msg);
msg_not_copied = 1;
pthread_mutex_unlock(&mutex_msg);
printf("nSERVER %d: message copiedn", getpid());
/* FIN while */
/* Fin main */


This is the process I follow to compile:



gcc -Wall -c keys.c
ar -rv libkeys.a keys.o
gcc -Wall -o client client.c libkeys.a -pthread -lrt
gcc server.c -o server -pthread -lrt


Once I firstly run ./server, and 6 seconds later (nothing important) I run ./client I get this output:



Iniciamos el servidor 

Server queue created succesgully

SERVER 9139: En 6s empiezo a buscar mensajes... //In 6 seconds I will start looking for messages

SERVER 9139: buscando mensajes... /Now run ./client

SERVER 9139: mensaje recibido
Current working dir: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES
El directorio que se va a eliminar es: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/result
No se que se va a printear pero weno 0
SERVER: Saliendo del init
Segmentation fault


The output that I get from gdb:



For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/core: No such file or directory.
(gdb) r
Starting program: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Iniciamos el servidor

Server queue created succesgully

SERVER 21039: En 6s empiezo a buscar mensajes...

SERVER 21039: buscando mensajes...

SERVER 21039: mensaje recibido
[New Thread 0x7ffff7dbe700 (LWP 21120)]

Thread 2 "a.out" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff7dbe700 (LWP 21120)]
__mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
37 ../sysdeps/unix/sysv/linux/mq_open.c: No such file or directory.
(gdb) b
Breakpoint 1 at 0x7ffff7f8788e: file ../sysdeps/unix/sysv/linux/mq_open.c, line 37.
(gdb) bt
#0 __mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
#1 0x0000555555555e1c in process_message (msg=0x7fffffffde60) at server.c:437
#2 0x00007ffff7f94fa3 in start_thread (arg=<optimized out>) at pthread_create.c:486
#3 0x00007ffff7ebb88f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95


If you require any other information, please ask me to do it specifying how to make it, because I am not expert in this.










share|improve this question



















  • 3





    Using void main() on a Unix-based program is just wrong (even though it is allowed by MS on Windows as an extension). Don't use it — use int main(void).

    – Jonathan Leffler
    Mar 8 at 0:01











  • And I skimmed two times through your 800 lines of code, and could find nothing (except void main() and other bad style.) BTW:can you guarantee that the files (and subdirs) are removed (recursively) before the parent directories?

    – wildplasser
    Mar 8 at 0:09












  • What is the question? Have you tried working with your fellow students?

    – Ben
    Mar 8 at 0:16












  • Too large. Reduce your reproduction.

    – Joshua
    Mar 8 at 0:30






  • 2





    @DavidSanchezGracia, you need to severely cut down on the amount of code. We can't debug hundreds of lines of code for you. A way for you to both help yourself solve it and us to help you with it is to eliminate all code that isn't necessary to demonstrate the error. See stackoverflow.com/help/mcve

    – brothir
    Mar 8 at 0:41















-1















Please take in mind that I don't want anyone to do my homework, but I have been almost three days unable to fix this problem and I don't feel I have the capacity to fix it soon. Here I go:



I am asked to do a POSIX communication system between several clients and a server. In order to do that I made the following code, every time a client send a request and the server receives it, the server makes a new thread that will manage the request.



Due to the problem I will try to explain now I have tried to redesign the hole code so now it is kind a mess.
The problem is that in any time after the server start a thread to handle the request I get a segmentation error.
Now I will post every piece of code required to reproduce the problem, and output example and the debug provided by gdb.



This is the client.c code



#include "libkeys.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>


void main()

char* key1="KEY1";
char* key2="KEY2";
char* key3="KEY3";
char* value11="VALUE11";
char* value12="VALUE12";
char* value13="VALUE13";
float value21=1.111;
float value22=2.222;
float value23=3.333;

float *p_value21=&value21;
float *p_value22=&value22;
float *p_value23=&value23;

printf("nCLIENT: Los valores se han seteado, va a proceder a ejecutarse initn");
init();

printf("nCLIENT: A partir de aqui no funciona ni de blasn");
/*set_value(key1, value11, value21);
set_value(key2, value12, value22);
set_value(key3, value13, value23);

printf("%dn",get_value( key1, value11, p_value21));
printf("VALUE1 %s n",value11);
printf("VALUE2 %f n",value21);

modify_value(key2, value13, p_value23);
printf("%dn",get_value( key2, value13, &value23));
printf("VALUE1 %s n",value13);
printf("VALUE2 %f n",value23);

printf("Num of items: %dn", num_items());
set_value(key3, value11, value23);
printf("Num of items: %dn", num_items());
delete_key(key1);
printf("Num of items: %dn", num_items());
exist(key1);
init();
exist(key1);
printf("Num of items: %dn", num_items());*/




Now, the library that client.c uses, called keys.c:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>

int NumberOfItems=0;



struct data
char value1[255];
float value2;
;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
printf("n CLIENT: Iniciamos int: n");
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=9;
attr.mq_msgsize=sizeof(int);

int client_pidINT=getpid();
char client_pidCHAR= (char) client_pidINT;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",client_pidINT);
//sprint saco el pid del cliente
printf("n CLIENT: Vamos a generar las colas");
q_client=mq_open(p_client_pidCHAR, O_CREAT

int set_value(char *key,char *value1, float value2)
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=1;
attr.mq_msgsize=sizeof(int);
//sprint saco el pid del cliente
q_client=mq_open("CLIENT_ONE", O_CREAT

int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
NumberOfItems--;
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

NumberOfItems--;


int num_items()
return NumberOfItems;



This is the library libkeys.h



#ifndef KEYAPI
#define KEYAPI

int init();

int set_value(char *key,char *value1, float value2);

int get_value(char *key, char *value1, float *value2);

int modify_value(char *key, char *value1, float *value2);

int exist(char *key);

int delete_key (char *key);

int num_items();

#endif


Finally this is the server.c code:



#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
/* mutex and condition variables for the message copy */
pthread_mutex_t mutex_msg;
int msg_not_copied = 1;
/* TRUE = 1 */
pthread_cond_t cond_msg;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;

//////////////////////////////////////////////////////////////////////FUNCIONES/////////////////////////////////////////////////////////////



int NumberOfItems=0;

pthread_mutex_t lock;






struct data
char value1[255];
float value2;
;



/**************************************************************************************************************************************************/
/****************************************************FUNCIONES*************************************************************************************/
/**************************************************************************************************************************************************/


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return -1;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);
/*if(rmdir(directory)==0)
printf("nSuccess removing the directoryn");
*/

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
return 0;


int set_value(char *key,char *value1, float value2)
FILE *ptr;
key=KeyForm(key);
printf("La clave creada es: %s",key);

if(ptr=fopen(key, "r"))
fclose(ptr);
printf("nEl archivo ya existen");
return -1;

printf("n El archivo no existia asi que se crea uno nuevo. n");
ptr=fopen(key, "w");
if (ptr ==NULL)
fprintf(stderr, "nError opend filen");
fclose(ptr);
exit (1);



char outputvalue1 [255];
int i;
for ( i = 0; i < 255; i++ )
outputvalue1[i]=*(value1 + i);


printf("El valor de la string es: %s", outputvalue1);

struct data input;
//input=value1,value2;
strcpy( input.value1, value1);
input.value2=value2;
printf("n string= %s n float= %f", input.value1, input.value2);
fwrite (&input,sizeof(struct data),1,ptr);

if(fwrite !=0) printf("n ha funcionado la escritura en el archvio n n");
else
printf ("se fue a la puta");
fclose (ptr);
return -1;

pthread_mutex_lock(&lock);
NumberOfItems++;
pthread_mutex_unlock(&lock);
fclose (ptr);
return 0;




int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);


int num_items()
pthread_mutex_lock(&lock);
return NumberOfItems;
pthread_mutex_unlock(&lock);



/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/





void process_message(struct mensaje *msg)
struct request msg_local; /* local message */
mqd_t q_client; /* client queue */

int result;

/* thread copies the message to local message*/
pthread_mutex_lock(&mutex_msg);
memcpy((char *) &msg_local, (char *)&msg, sizeof(struct request));

/* wake up server */
msg_not_copied = 0;
pthread_cond_signal(&cond_msg);
pthread_mutex_unlock(&mutex_msg);


char *p_key;
char *p_value1;
float *p_value2;

p_key=&msg_local.key;
p_value1=&msg_local.value1;
p_value2=&msg_local.value2;

/* execute client request and prepare reply */



result =0;

switch(msg_local.method)
//case 0 equivalent to init()
case 0:

int hola;
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
result =-1;
break;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
result=0;

break;


//case 1 equivalent to set_value
case 1: result=set_value(p_key, p_value1, msg_local.value2);break;


case 2: result=get_value(p_key, p_value1, p_value2);
break;

case 3: result=modify_value(p_key, p_value1, p_value2);
break;

case 4: result=delete_key(p_key);
break;

case 5: result=exist(p_key);
break;

case 6: result=num_items();
break;

default: printf("There was an error");
break;



// return result to client by sending it to queue
printf("ESTOY AQUIIIIIII Y EL RESULTADO ES: %d", result);
char client_pidCHAR= (char) msg_local.name;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",msg_local.name);
q_client = mq_open(client_pidCHAR, O_WRONLY); //msg_local.name es el nombre del cliente
// */
if (q_client == -1)
perror("Can't open client queue");
else
mq_send(q_client, (char *) &result, sizeof(int), 0);
mq_close(q_client);

pthread_exit(0);


///////////////////////////////MAIN/////////////////////
int main(void)O_RDONLY, 0700, &q_attr);

if (q_server == -1)
perror("Cant create server queue");
return 1;
else
printf(" n Server queue created succesgully n");


pthread_mutex_init(&mutex_msg, NULL);
pthread_cond_init(&cond_msg, NULL); //Iniziate the condition variable
pthread_attr_init(&t_attr);
/* thread atributes */
pthread_attr_setdetachstate(&t_attr, PTHREAD_CREATE_DETACHED);


for(;;)
printf("nSERVER %d: En 6s empiezo a buscar mensajes...n", getpid());
sleep(6);
printf("nSERVER %d: buscando mensajes...n", getpid());
if(mq_receive(q_server, &msg, sizeof(struct request), 0)==-1) //Poner en vez de 0 NULL al final?
printf("nSERVER %d: Error al recibir mensaje n", getpid());
else
printf("n SERVER %d: mensaje recibidon", getpid());

pthread_create(&thid, &t_attr, process_message, &msg);
sleep(6);
printf("nSERVER %d: copying the messagen", getpid());
/* wait for thread to copy message */
pthread_mutex_lock(&mutex_msg);
while (msg_not_copied)
pthread_cond_wait(&cond_msg, &mutex_msg);
msg_not_copied = 1;
pthread_mutex_unlock(&mutex_msg);
printf("nSERVER %d: message copiedn", getpid());
/* FIN while */
/* Fin main */


This is the process I follow to compile:



gcc -Wall -c keys.c
ar -rv libkeys.a keys.o
gcc -Wall -o client client.c libkeys.a -pthread -lrt
gcc server.c -o server -pthread -lrt


Once I firstly run ./server, and 6 seconds later (nothing important) I run ./client I get this output:



Iniciamos el servidor 

Server queue created succesgully

SERVER 9139: En 6s empiezo a buscar mensajes... //In 6 seconds I will start looking for messages

SERVER 9139: buscando mensajes... /Now run ./client

SERVER 9139: mensaje recibido
Current working dir: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES
El directorio que se va a eliminar es: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/result
No se que se va a printear pero weno 0
SERVER: Saliendo del init
Segmentation fault


The output that I get from gdb:



For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/core: No such file or directory.
(gdb) r
Starting program: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Iniciamos el servidor

Server queue created succesgully

SERVER 21039: En 6s empiezo a buscar mensajes...

SERVER 21039: buscando mensajes...

SERVER 21039: mensaje recibido
[New Thread 0x7ffff7dbe700 (LWP 21120)]

Thread 2 "a.out" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff7dbe700 (LWP 21120)]
__mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
37 ../sysdeps/unix/sysv/linux/mq_open.c: No such file or directory.
(gdb) b
Breakpoint 1 at 0x7ffff7f8788e: file ../sysdeps/unix/sysv/linux/mq_open.c, line 37.
(gdb) bt
#0 __mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
#1 0x0000555555555e1c in process_message (msg=0x7fffffffde60) at server.c:437
#2 0x00007ffff7f94fa3 in start_thread (arg=<optimized out>) at pthread_create.c:486
#3 0x00007ffff7ebb88f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95


If you require any other information, please ask me to do it specifying how to make it, because I am not expert in this.










share|improve this question



















  • 3





    Using void main() on a Unix-based program is just wrong (even though it is allowed by MS on Windows as an extension). Don't use it — use int main(void).

    – Jonathan Leffler
    Mar 8 at 0:01











  • And I skimmed two times through your 800 lines of code, and could find nothing (except void main() and other bad style.) BTW:can you guarantee that the files (and subdirs) are removed (recursively) before the parent directories?

    – wildplasser
    Mar 8 at 0:09












  • What is the question? Have you tried working with your fellow students?

    – Ben
    Mar 8 at 0:16












  • Too large. Reduce your reproduction.

    – Joshua
    Mar 8 at 0:30






  • 2





    @DavidSanchezGracia, you need to severely cut down on the amount of code. We can't debug hundreds of lines of code for you. A way for you to both help yourself solve it and us to help you with it is to eliminate all code that isn't necessary to demonstrate the error. See stackoverflow.com/help/mcve

    – brothir
    Mar 8 at 0:41













-1












-1








-1








Please take in mind that I don't want anyone to do my homework, but I have been almost three days unable to fix this problem and I don't feel I have the capacity to fix it soon. Here I go:



I am asked to do a POSIX communication system between several clients and a server. In order to do that I made the following code, every time a client send a request and the server receives it, the server makes a new thread that will manage the request.



Due to the problem I will try to explain now I have tried to redesign the hole code so now it is kind a mess.
The problem is that in any time after the server start a thread to handle the request I get a segmentation error.
Now I will post every piece of code required to reproduce the problem, and output example and the debug provided by gdb.



This is the client.c code



#include "libkeys.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>


void main()

char* key1="KEY1";
char* key2="KEY2";
char* key3="KEY3";
char* value11="VALUE11";
char* value12="VALUE12";
char* value13="VALUE13";
float value21=1.111;
float value22=2.222;
float value23=3.333;

float *p_value21=&value21;
float *p_value22=&value22;
float *p_value23=&value23;

printf("nCLIENT: Los valores se han seteado, va a proceder a ejecutarse initn");
init();

printf("nCLIENT: A partir de aqui no funciona ni de blasn");
/*set_value(key1, value11, value21);
set_value(key2, value12, value22);
set_value(key3, value13, value23);

printf("%dn",get_value( key1, value11, p_value21));
printf("VALUE1 %s n",value11);
printf("VALUE2 %f n",value21);

modify_value(key2, value13, p_value23);
printf("%dn",get_value( key2, value13, &value23));
printf("VALUE1 %s n",value13);
printf("VALUE2 %f n",value23);

printf("Num of items: %dn", num_items());
set_value(key3, value11, value23);
printf("Num of items: %dn", num_items());
delete_key(key1);
printf("Num of items: %dn", num_items());
exist(key1);
init();
exist(key1);
printf("Num of items: %dn", num_items());*/




Now, the library that client.c uses, called keys.c:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>

int NumberOfItems=0;



struct data
char value1[255];
float value2;
;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
printf("n CLIENT: Iniciamos int: n");
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=9;
attr.mq_msgsize=sizeof(int);

int client_pidINT=getpid();
char client_pidCHAR= (char) client_pidINT;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",client_pidINT);
//sprint saco el pid del cliente
printf("n CLIENT: Vamos a generar las colas");
q_client=mq_open(p_client_pidCHAR, O_CREAT

int set_value(char *key,char *value1, float value2)
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=1;
attr.mq_msgsize=sizeof(int);
//sprint saco el pid del cliente
q_client=mq_open("CLIENT_ONE", O_CREAT

int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
NumberOfItems--;
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

NumberOfItems--;


int num_items()
return NumberOfItems;



This is the library libkeys.h



#ifndef KEYAPI
#define KEYAPI

int init();

int set_value(char *key,char *value1, float value2);

int get_value(char *key, char *value1, float *value2);

int modify_value(char *key, char *value1, float *value2);

int exist(char *key);

int delete_key (char *key);

int num_items();

#endif


Finally this is the server.c code:



#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
/* mutex and condition variables for the message copy */
pthread_mutex_t mutex_msg;
int msg_not_copied = 1;
/* TRUE = 1 */
pthread_cond_t cond_msg;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;

//////////////////////////////////////////////////////////////////////FUNCIONES/////////////////////////////////////////////////////////////



int NumberOfItems=0;

pthread_mutex_t lock;






struct data
char value1[255];
float value2;
;



/**************************************************************************************************************************************************/
/****************************************************FUNCIONES*************************************************************************************/
/**************************************************************************************************************************************************/


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return -1;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);
/*if(rmdir(directory)==0)
printf("nSuccess removing the directoryn");
*/

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
return 0;


int set_value(char *key,char *value1, float value2)
FILE *ptr;
key=KeyForm(key);
printf("La clave creada es: %s",key);

if(ptr=fopen(key, "r"))
fclose(ptr);
printf("nEl archivo ya existen");
return -1;

printf("n El archivo no existia asi que se crea uno nuevo. n");
ptr=fopen(key, "w");
if (ptr ==NULL)
fprintf(stderr, "nError opend filen");
fclose(ptr);
exit (1);



char outputvalue1 [255];
int i;
for ( i = 0; i < 255; i++ )
outputvalue1[i]=*(value1 + i);


printf("El valor de la string es: %s", outputvalue1);

struct data input;
//input=value1,value2;
strcpy( input.value1, value1);
input.value2=value2;
printf("n string= %s n float= %f", input.value1, input.value2);
fwrite (&input,sizeof(struct data),1,ptr);

if(fwrite !=0) printf("n ha funcionado la escritura en el archvio n n");
else
printf ("se fue a la puta");
fclose (ptr);
return -1;

pthread_mutex_lock(&lock);
NumberOfItems++;
pthread_mutex_unlock(&lock);
fclose (ptr);
return 0;




int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);


int num_items()
pthread_mutex_lock(&lock);
return NumberOfItems;
pthread_mutex_unlock(&lock);



/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/





void process_message(struct mensaje *msg)
struct request msg_local; /* local message */
mqd_t q_client; /* client queue */

int result;

/* thread copies the message to local message*/
pthread_mutex_lock(&mutex_msg);
memcpy((char *) &msg_local, (char *)&msg, sizeof(struct request));

/* wake up server */
msg_not_copied = 0;
pthread_cond_signal(&cond_msg);
pthread_mutex_unlock(&mutex_msg);


char *p_key;
char *p_value1;
float *p_value2;

p_key=&msg_local.key;
p_value1=&msg_local.value1;
p_value2=&msg_local.value2;

/* execute client request and prepare reply */



result =0;

switch(msg_local.method)
//case 0 equivalent to init()
case 0:

int hola;
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
result =-1;
break;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
result=0;

break;


//case 1 equivalent to set_value
case 1: result=set_value(p_key, p_value1, msg_local.value2);break;


case 2: result=get_value(p_key, p_value1, p_value2);
break;

case 3: result=modify_value(p_key, p_value1, p_value2);
break;

case 4: result=delete_key(p_key);
break;

case 5: result=exist(p_key);
break;

case 6: result=num_items();
break;

default: printf("There was an error");
break;



// return result to client by sending it to queue
printf("ESTOY AQUIIIIIII Y EL RESULTADO ES: %d", result);
char client_pidCHAR= (char) msg_local.name;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",msg_local.name);
q_client = mq_open(client_pidCHAR, O_WRONLY); //msg_local.name es el nombre del cliente
// */
if (q_client == -1)
perror("Can't open client queue");
else
mq_send(q_client, (char *) &result, sizeof(int), 0);
mq_close(q_client);

pthread_exit(0);


///////////////////////////////MAIN/////////////////////
int main(void)O_RDONLY, 0700, &q_attr);

if (q_server == -1)
perror("Cant create server queue");
return 1;
else
printf(" n Server queue created succesgully n");


pthread_mutex_init(&mutex_msg, NULL);
pthread_cond_init(&cond_msg, NULL); //Iniziate the condition variable
pthread_attr_init(&t_attr);
/* thread atributes */
pthread_attr_setdetachstate(&t_attr, PTHREAD_CREATE_DETACHED);


for(;;)
printf("nSERVER %d: En 6s empiezo a buscar mensajes...n", getpid());
sleep(6);
printf("nSERVER %d: buscando mensajes...n", getpid());
if(mq_receive(q_server, &msg, sizeof(struct request), 0)==-1) //Poner en vez de 0 NULL al final?
printf("nSERVER %d: Error al recibir mensaje n", getpid());
else
printf("n SERVER %d: mensaje recibidon", getpid());

pthread_create(&thid, &t_attr, process_message, &msg);
sleep(6);
printf("nSERVER %d: copying the messagen", getpid());
/* wait for thread to copy message */
pthread_mutex_lock(&mutex_msg);
while (msg_not_copied)
pthread_cond_wait(&cond_msg, &mutex_msg);
msg_not_copied = 1;
pthread_mutex_unlock(&mutex_msg);
printf("nSERVER %d: message copiedn", getpid());
/* FIN while */
/* Fin main */


This is the process I follow to compile:



gcc -Wall -c keys.c
ar -rv libkeys.a keys.o
gcc -Wall -o client client.c libkeys.a -pthread -lrt
gcc server.c -o server -pthread -lrt


Once I firstly run ./server, and 6 seconds later (nothing important) I run ./client I get this output:



Iniciamos el servidor 

Server queue created succesgully

SERVER 9139: En 6s empiezo a buscar mensajes... //In 6 seconds I will start looking for messages

SERVER 9139: buscando mensajes... /Now run ./client

SERVER 9139: mensaje recibido
Current working dir: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES
El directorio que se va a eliminar es: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/result
No se que se va a printear pero weno 0
SERVER: Saliendo del init
Segmentation fault


The output that I get from gdb:



For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/core: No such file or directory.
(gdb) r
Starting program: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Iniciamos el servidor

Server queue created succesgully

SERVER 21039: En 6s empiezo a buscar mensajes...

SERVER 21039: buscando mensajes...

SERVER 21039: mensaje recibido
[New Thread 0x7ffff7dbe700 (LWP 21120)]

Thread 2 "a.out" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff7dbe700 (LWP 21120)]
__mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
37 ../sysdeps/unix/sysv/linux/mq_open.c: No such file or directory.
(gdb) b
Breakpoint 1 at 0x7ffff7f8788e: file ../sysdeps/unix/sysv/linux/mq_open.c, line 37.
(gdb) bt
#0 __mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
#1 0x0000555555555e1c in process_message (msg=0x7fffffffde60) at server.c:437
#2 0x00007ffff7f94fa3 in start_thread (arg=<optimized out>) at pthread_create.c:486
#3 0x00007ffff7ebb88f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95


If you require any other information, please ask me to do it specifying how to make it, because I am not expert in this.










share|improve this question
















Please take in mind that I don't want anyone to do my homework, but I have been almost three days unable to fix this problem and I don't feel I have the capacity to fix it soon. Here I go:



I am asked to do a POSIX communication system between several clients and a server. In order to do that I made the following code, every time a client send a request and the server receives it, the server makes a new thread that will manage the request.



Due to the problem I will try to explain now I have tried to redesign the hole code so now it is kind a mess.
The problem is that in any time after the server start a thread to handle the request I get a segmentation error.
Now I will post every piece of code required to reproduce the problem, and output example and the debug provided by gdb.



This is the client.c code



#include "libkeys.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>


void main()

char* key1="KEY1";
char* key2="KEY2";
char* key3="KEY3";
char* value11="VALUE11";
char* value12="VALUE12";
char* value13="VALUE13";
float value21=1.111;
float value22=2.222;
float value23=3.333;

float *p_value21=&value21;
float *p_value22=&value22;
float *p_value23=&value23;

printf("nCLIENT: Los valores se han seteado, va a proceder a ejecutarse initn");
init();

printf("nCLIENT: A partir de aqui no funciona ni de blasn");
/*set_value(key1, value11, value21);
set_value(key2, value12, value22);
set_value(key3, value13, value23);

printf("%dn",get_value( key1, value11, p_value21));
printf("VALUE1 %s n",value11);
printf("VALUE2 %f n",value21);

modify_value(key2, value13, p_value23);
printf("%dn",get_value( key2, value13, &value23));
printf("VALUE1 %s n",value13);
printf("VALUE2 %f n",value23);

printf("Num of items: %dn", num_items());
set_value(key3, value11, value23);
printf("Num of items: %dn", num_items());
delete_key(key1);
printf("Num of items: %dn", num_items());
exist(key1);
init();
exist(key1);
printf("Num of items: %dn", num_items());*/




Now, the library that client.c uses, called keys.c:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>

int NumberOfItems=0;



struct data
char value1[255];
float value2;
;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
printf("n CLIENT: Iniciamos int: n");
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=9;
attr.mq_msgsize=sizeof(int);

int client_pidINT=getpid();
char client_pidCHAR= (char) client_pidINT;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",client_pidINT);
//sprint saco el pid del cliente
printf("n CLIENT: Vamos a generar las colas");
q_client=mq_open(p_client_pidCHAR, O_CREAT

int set_value(char *key,char *value1, float value2)
mqd_t q_server;
mqd_t q_client;

struct request req;
int res;
struct mq_attr attr;

attr.mq_maxmsg=1;
attr.mq_msgsize=sizeof(int);
//sprint saco el pid del cliente
q_client=mq_open("CLIENT_ONE", O_CREAT

int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
NumberOfItems--;
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

NumberOfItems--;


int num_items()
return NumberOfItems;



This is the library libkeys.h



#ifndef KEYAPI
#define KEYAPI

int init();

int set_value(char *key,char *value1, float value2);

int get_value(char *key, char *value1, float *value2);

int modify_value(char *key, char *value1, float *value2);

int exist(char *key);

int delete_key (char *key);

int num_items();

#endif


Finally this is the server.c code:



#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
/* mutex and condition variables for the message copy */
pthread_mutex_t mutex_msg;
int msg_not_copied = 1;
/* TRUE = 1 */
pthread_cond_t cond_msg;

struct request
int name; //int pid del cliente
char key[255];
char value1[255];
float value2;
int method;
;

//////////////////////////////////////////////////////////////////////FUNCIONES/////////////////////////////////////////////////////////////



int NumberOfItems=0;

pthread_mutex_t lock;






struct data
char value1[255];
float value2;
;



/**************************************************************************************************************************************************/
/****************************************************FUNCIONES*************************************************************************************/
/**************************************************************************************************************************************************/


char* concat(const char *s1, const char *s2)
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;


char* KeyForm(const char *s1)
char dir[]="./result/";
char *p_dir=dir;

char *result = malloc(strlen(p_dir) + strlen(s1) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, p_dir);
strcat(result, s1);
return result;


int Obtain_Directory()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return 1;

return 0;


int remove_directory(const char *path)
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;

if (d)
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) !strcmp(p->d_name, ".."))
continue;

len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);

if (buf)
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf))
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);

else
r2 = unlink(buf);


free(buf);

r = r2;

closedir(d);

if (!r)
r = rmdir(path);

return r;


int init()
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
return -1;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);
/*if(rmdir(directory)==0)
printf("nSuccess removing the directoryn");
*/

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
return 0;


int set_value(char *key,char *value1, float value2)
FILE *ptr;
key=KeyForm(key);
printf("La clave creada es: %s",key);

if(ptr=fopen(key, "r"))
fclose(ptr);
printf("nEl archivo ya existen");
return -1;

printf("n El archivo no existia asi que se crea uno nuevo. n");
ptr=fopen(key, "w");
if (ptr ==NULL)
fprintf(stderr, "nError opend filen");
fclose(ptr);
exit (1);



char outputvalue1 [255];
int i;
for ( i = 0; i < 255; i++ )
outputvalue1[i]=*(value1 + i);


printf("El valor de la string es: %s", outputvalue1);

struct data input;
//input=value1,value2;
strcpy( input.value1, value1);
input.value2=value2;
printf("n string= %s n float= %f", input.value1, input.value2);
fwrite (&input,sizeof(struct data),1,ptr);

if(fwrite !=0) printf("n ha funcionado la escritura en el archvio n n");
else
printf ("se fue a la puta");
fclose (ptr);
return -1;

pthread_mutex_lock(&lock);
NumberOfItems++;
pthread_mutex_unlock(&lock);
fclose (ptr);
return 0;




int get_value(char *key, char *value1, float *value2)
FILE *ptr;
key=KeyForm(key);
struct data datita;
if(ptr=fopen(key, "r"))
if(ptr == NULL)
printf("ha habido un error al abrir el archivo");
return -1;

printf("nEl archivo existen");
while(fread(&datita, sizeof(struct data),1,ptr))
printf("n string= %s n float= %f n", datita.value1, datita.value2);

char hola[] ="hola";
char *v1=datita.value1;
float v2=datita.value2;

printf ("n Ha terminado de pasarse el contenido del archivo a los pointers dadosn");

fclose(ptr);
return 0;
else
printf("nEl archivo no exiten ");
return -1;




int modify_value(char *key, char *value1, float *value2)
char *alteredkey=KeyForm(key);
printf("estamos empezando a modificar los valores n");
if(exist(alteredkey))
printf("La key que antes de modificar vamos a eliminar es: %s",key);
if(delete_key(alteredkey)==0)
//strcpy( input.value1, value1);
float v2=*value2;
printf("nusamos set valuen");
if(set_value(key,value1,v2)==0)
printf("n Modificacion realizada con exito, resto uno al totaln");
pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);
return 0;
else
printf("nError en setvaluen");
return -1;

else
printf("nError: al deleten");
return -1;

else
printf("nError: al exist o no existen");
return -1;



int exist(char *key)
printf("BUSCAMOOOOS");
FILE *ptr;


if(ptr=fopen(key, "r"))
if(ptr==NULL)
printf("Error al buscar");
return -1;

fclose(ptr);
printf("nSep, el archivo existen");
return 1;
else
fclose(ptr);
if(ptr==NULL)
printf("Error al buscar");
return -1;

printf("Nop, el archivo no exite");
return 0;



int delete_key (char *key)
if (remove(key)==0)
printf("nEliminado del mapan");
return 0;
else
printf("n Sobrevives hoy pa morir mañanan");
return -1;

pthread_mutex_lock(&lock);
NumberOfItems--;
pthread_mutex_unlock(&lock);


int num_items()
pthread_mutex_lock(&lock);
return NumberOfItems;
pthread_mutex_unlock(&lock);



/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/
/**************************************************************************************************************************************************/





void process_message(struct mensaje *msg)
struct request msg_local; /* local message */
mqd_t q_client; /* client queue */

int result;

/* thread copies the message to local message*/
pthread_mutex_lock(&mutex_msg);
memcpy((char *) &msg_local, (char *)&msg, sizeof(struct request));

/* wake up server */
msg_not_copied = 0;
pthread_cond_signal(&cond_msg);
pthread_mutex_unlock(&mutex_msg);


char *p_key;
char *p_value1;
float *p_value2;

p_key=&msg_local.key;
p_value1=&msg_local.value1;
p_value2=&msg_local.value2;

/* execute client request and prepare reply */



result =0;

switch(msg_local.method)
//case 0 equivalent to init()
case 0:

int hola;
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("Current working dir: %sn", cwd);
else
perror("getcwd() error");
result =-1;
break;

char *directory;
directory=cwd;
char addpath[]="/result";
char *p_addpath=&addpath;
directory=concat(directory,p_addpath);
printf("El directorio que se va a eliminar es: %s", directory);

printf("n No se que se va a printear pero weno %d",remove_directory(directory));

system ("mkdir result"); //The new directory is generated


NumberOfItems=0; //Reset the number of items;
printf("n SERVER: Saliendo del initn");
sleep(5);
result=0;

break;


//case 1 equivalent to set_value
case 1: result=set_value(p_key, p_value1, msg_local.value2);break;


case 2: result=get_value(p_key, p_value1, p_value2);
break;

case 3: result=modify_value(p_key, p_value1, p_value2);
break;

case 4: result=delete_key(p_key);
break;

case 5: result=exist(p_key);
break;

case 6: result=num_items();
break;

default: printf("There was an error");
break;



// return result to client by sending it to queue
printf("ESTOY AQUIIIIIII Y EL RESULTADO ES: %d", result);
char client_pidCHAR= (char) msg_local.name;
char *p_client_pidCHAR=&client_pidCHAR;
printf("EL nombre de la queue del client es: %d",msg_local.name);
q_client = mq_open(client_pidCHAR, O_WRONLY); //msg_local.name es el nombre del cliente
// */
if (q_client == -1)
perror("Can't open client queue");
else
mq_send(q_client, (char *) &result, sizeof(int), 0);
mq_close(q_client);

pthread_exit(0);


///////////////////////////////MAIN/////////////////////
int main(void)O_RDONLY, 0700, &q_attr);

if (q_server == -1)
perror("Cant create server queue");
return 1;
else
printf(" n Server queue created succesgully n");


pthread_mutex_init(&mutex_msg, NULL);
pthread_cond_init(&cond_msg, NULL); //Iniziate the condition variable
pthread_attr_init(&t_attr);
/* thread atributes */
pthread_attr_setdetachstate(&t_attr, PTHREAD_CREATE_DETACHED);


for(;;)
printf("nSERVER %d: En 6s empiezo a buscar mensajes...n", getpid());
sleep(6);
printf("nSERVER %d: buscando mensajes...n", getpid());
if(mq_receive(q_server, &msg, sizeof(struct request), 0)==-1) //Poner en vez de 0 NULL al final?
printf("nSERVER %d: Error al recibir mensaje n", getpid());
else
printf("n SERVER %d: mensaje recibidon", getpid());

pthread_create(&thid, &t_attr, process_message, &msg);
sleep(6);
printf("nSERVER %d: copying the messagen", getpid());
/* wait for thread to copy message */
pthread_mutex_lock(&mutex_msg);
while (msg_not_copied)
pthread_cond_wait(&cond_msg, &mutex_msg);
msg_not_copied = 1;
pthread_mutex_unlock(&mutex_msg);
printf("nSERVER %d: message copiedn", getpid());
/* FIN while */
/* Fin main */


This is the process I follow to compile:



gcc -Wall -c keys.c
ar -rv libkeys.a keys.o
gcc -Wall -o client client.c libkeys.a -pthread -lrt
gcc server.c -o server -pthread -lrt


Once I firstly run ./server, and 6 seconds later (nothing important) I run ./client I get this output:



Iniciamos el servidor 

Server queue created succesgully

SERVER 9139: En 6s empiezo a buscar mensajes... //In 6 seconds I will start looking for messages

SERVER 9139: buscando mensajes... /Now run ./client

SERVER 9139: mensaje recibido
Current working dir: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES
El directorio que se va a eliminar es: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/result
No se que se va a printear pero weno 0
SERVER: Saliendo del init
Segmentation fault


The output that I get from gdb:



For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/core: No such file or directory.
(gdb) r
Starting program: /home/david/Documents/Sistemas-Distribuidos/Labs/lab1/FINAL_PICTURES/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Iniciamos el servidor

Server queue created succesgully

SERVER 21039: En 6s empiezo a buscar mensajes...

SERVER 21039: buscando mensajes...

SERVER 21039: mensaje recibido
[New Thread 0x7ffff7dbe700 (LWP 21120)]

Thread 2 "a.out" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff7dbe700 (LWP 21120)]
__mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
37 ../sysdeps/unix/sysv/linux/mq_open.c: No such file or directory.
(gdb) b
Breakpoint 1 at 0x7ffff7f8788e: file ../sysdeps/unix/sysv/linux/mq_open.c, line 37.
(gdb) bt
#0 __mq_open (name=0x60 <error: Cannot access memory at address 0x60>, oflag=1)
at ../sysdeps/unix/sysv/linux/mq_open.c:37
#1 0x0000555555555e1c in process_message (msg=0x7fffffffde60) at server.c:437
#2 0x00007ffff7f94fa3 in start_thread (arg=<optimized out>) at pthread_create.c:486
#3 0x00007ffff7ebb88f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95


If you require any other information, please ask me to do it specifying how to make it, because I am not expert in this.







c






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 23:58









Jonathan Leffler

572k926861037




572k926861037










asked Mar 7 at 23:53









David Sanchez GraciaDavid Sanchez Gracia

21




21







  • 3





    Using void main() on a Unix-based program is just wrong (even though it is allowed by MS on Windows as an extension). Don't use it — use int main(void).

    – Jonathan Leffler
    Mar 8 at 0:01











  • And I skimmed two times through your 800 lines of code, and could find nothing (except void main() and other bad style.) BTW:can you guarantee that the files (and subdirs) are removed (recursively) before the parent directories?

    – wildplasser
    Mar 8 at 0:09












  • What is the question? Have you tried working with your fellow students?

    – Ben
    Mar 8 at 0:16












  • Too large. Reduce your reproduction.

    – Joshua
    Mar 8 at 0:30






  • 2





    @DavidSanchezGracia, you need to severely cut down on the amount of code. We can't debug hundreds of lines of code for you. A way for you to both help yourself solve it and us to help you with it is to eliminate all code that isn't necessary to demonstrate the error. See stackoverflow.com/help/mcve

    – brothir
    Mar 8 at 0:41












  • 3





    Using void main() on a Unix-based program is just wrong (even though it is allowed by MS on Windows as an extension). Don't use it — use int main(void).

    – Jonathan Leffler
    Mar 8 at 0:01











  • And I skimmed two times through your 800 lines of code, and could find nothing (except void main() and other bad style.) BTW:can you guarantee that the files (and subdirs) are removed (recursively) before the parent directories?

    – wildplasser
    Mar 8 at 0:09












  • What is the question? Have you tried working with your fellow students?

    – Ben
    Mar 8 at 0:16












  • Too large. Reduce your reproduction.

    – Joshua
    Mar 8 at 0:30






  • 2





    @DavidSanchezGracia, you need to severely cut down on the amount of code. We can't debug hundreds of lines of code for you. A way for you to both help yourself solve it and us to help you with it is to eliminate all code that isn't necessary to demonstrate the error. See stackoverflow.com/help/mcve

    – brothir
    Mar 8 at 0:41







3




3





Using void main() on a Unix-based program is just wrong (even though it is allowed by MS on Windows as an extension). Don't use it — use int main(void).

– Jonathan Leffler
Mar 8 at 0:01





Using void main() on a Unix-based program is just wrong (even though it is allowed by MS on Windows as an extension). Don't use it — use int main(void).

– Jonathan Leffler
Mar 8 at 0:01













And I skimmed two times through your 800 lines of code, and could find nothing (except void main() and other bad style.) BTW:can you guarantee that the files (and subdirs) are removed (recursively) before the parent directories?

– wildplasser
Mar 8 at 0:09






And I skimmed two times through your 800 lines of code, and could find nothing (except void main() and other bad style.) BTW:can you guarantee that the files (and subdirs) are removed (recursively) before the parent directories?

– wildplasser
Mar 8 at 0:09














What is the question? Have you tried working with your fellow students?

– Ben
Mar 8 at 0:16






What is the question? Have you tried working with your fellow students?

– Ben
Mar 8 at 0:16














Too large. Reduce your reproduction.

– Joshua
Mar 8 at 0:30





Too large. Reduce your reproduction.

– Joshua
Mar 8 at 0:30




2




2





@DavidSanchezGracia, you need to severely cut down on the amount of code. We can't debug hundreds of lines of code for you. A way for you to both help yourself solve it and us to help you with it is to eliminate all code that isn't necessary to demonstrate the error. See stackoverflow.com/help/mcve

– brothir
Mar 8 at 0:41





@DavidSanchezGracia, you need to severely cut down on the amount of code. We can't debug hundreds of lines of code for you. A way for you to both help yourself solve it and us to help you with it is to eliminate all code that isn't necessary to demonstrate the error. See stackoverflow.com/help/mcve

– brothir
Mar 8 at 0:41












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054678%2freceived-signal-sigsegv-segmentation-fault-c-progran-for-message-posix-communi%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054678%2freceived-signal-sigsegv-segmentation-fault-c-progran-for-message-posix-communi%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived