Reputation: 2225
I'm writing a program that has a number of child processes. The parent has two pipes to write to the child, each pipe is dup2ed into a separate file descriptor in the child. The parent reads through a script file with a number of commands to work what it needs to do. This seems to work fine except I've noticed that if I try to close a pipe from parent to child then if the next line in the script file is fully blank it will be read in weirdly. If I print it out then it comes out as ���<
which my program (understandably) doesn't know what to do with.
There is seemingly no link at all between the file pointer that I'm reading in from and the pipe that I'm closing.
My code for reading in lines in is below. It works perfectly normally, just in this case it doesn't work properly and I can't work out why.
char *get_script_line(FILE *script)
{
char *line;
char charRead;
int placeInStr = 0;
int currentSizeOfStr = 80;
int maxStrLength = 64;
/* initialize the line */
line = (char *)malloc(sizeof(char)*currentSizeOfStr);
while ((charRead = fgetc(script)) != EOF && charRead != '\n') {
/* read each char from input and put it in the array */
line[placeInStr] = charRead;
placeInStr++;
if (placeInStr == currentSizeOfStr) {
/* array will run out of room, need to allocate */
/* some more space */
currentSizeOfStr = placeInStr + maxStrLength;
line = realloc(line, currentSizeOfStr);
}
}
if (charRead == EOF && placeInStr == 0)
{
/* EOF, return null */
return NULL;
}
return line;
}
And when I close a pipe I'm doing this:
fflush(pipe);
fclose(pipe);
Does anyone have any idea of what I might be doing wrong? Or have some sort of an idea of how to debug this problem?
edit: To be clear my input script might (basically) look something like this:
Start a new child and set up pipes etc
Send EOF to one of the pipes to the child
(BLANK LINE)
Do something else
It works fine otherwise and I'm fairly sure I'm closing the pipes as I'm doing will send EOF as its supposed to.
Upvotes: 0
Views: 192
Reputation: 2225
Actually.. think I just fixed it. I wasn't freeing the line in get_script_line when I was done with it but once I put that in it has all started working correctly. I have no idea why that would have an effect though.. would be interested if anyone could tell me why not freeing memory could have that effect?
Upvotes: 0
Reputation: 249592
I suggest running your program under valgrind to check for memory errors.
Upvotes: 1