开发者

Segmentation fault while accessing struct filled with data read from pipe

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);


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜