0
votes

I keep on having a segmentation fault while trying to access a struct named Request, filled with data read from a pipe. What's wrong with my code? The error is thrown here with a simple printf trying to print the name field

STRUCT DEFINITION:

typedef struct 
{
    char code;      
    pid_t pid;       
    char *name;      
    char *object;    
    int id;          
    void *buffer;    
    size_t size;     
} Request;

WRITER CODE:

request.code   = MANADDUSER;   /* macro defining a char */
request.pid    = getpid();
request.name   = argument1;   /* dinamycally allocated string */
request.object = NULL;
request.id     = 0;
request.buffer = NULL;
request.size   = 0;
if((fifoto = open(FIFOTOMMBOXD, O_WRONLY)) == -1)   logMmboxman("error in opening FIFOTO\n", 1); 
else                                                logMmboxman("opened FIFOTO\n", 0);  

if((write(fifoto, &request, sizeof(Request))) != sizeof(Request))   logMmboxman("error in writing FIFOTO\n", 1);
else                                                                logMmboxman("written on FIFOTO\n", 0);
close(fifoto);

READER CODE:

if((fifoto = open(FIFOTOMMBOXD, O_RDWR)) == -1)   logMmboxd("error in opening FIFOTO\n", 1); 
else                                              logMmboxd("opened FIFOTO\n", 0);  

if((read(fifoto, &request, sizeof(Request))) != sizeof(Request))   logMmboxd("error in reading FIFOTO\n", 1);
else                                                               logMmboxd("read from FIFOTO\n", 0);
close(fifoto);

printf("%s\n", request.name);
3
Please don't write tags in titles. - Lightness Races in Orbit
Your code is not a testcase; in particular, it does not show the creation of the Request object. - Lightness Races in Orbit
where did you pick up this strange code formatting style? I have to say it's one I've never seen before. - Carl Norum
ok I won't use tags anymore. I posted just these statements to focus on the core of the problem. - Damiano Barbati

3 Answers

4
votes

You are probably sending the address of Request.name over the pipe. When the receiver gets it, Request.name obviously points to invalid memory.

2
votes

This can be fixed by altering the structure to something like:

typedef struct 
{
    char   code;      
    pid_t  pid;       
    char   name[SOMESIZE];
    char   object[SOMEOTHERSIZE];
    int    id;          
    size_t size;     
} Request;

and make corresponding changes to the reader and writer. If the pipe is connected between processes, the addresses contained by name, object, and buffer are meaningless in the new context.

1
votes

Are you passing the flag you expect to the open within the Reader's code?

I would have expected you want O_RDONLY rather than O_RDWR.