I’m attempting to write a structure consisting of a an array of characters, an integer value, and a pointer to a pipe. The structure represents a node in a singly linked list.
//Define a linked-list node object
typedef struct node{
char word[128];
int frequency;
struct node *next;
} NODE;
The object of the program is to use a pipe to pass a node from several concurrent child processes to the parent. The pipe structure I’ve implemented seems to work fine with regular character arrays but won’t work if I try to pass the entire node object.
//for each file argument, create a child process
for (i = 1; i < argc; i ++)
{
pipe(p[i-1]);
pid = fork();
if (pid == 0)
{
//child process
close(p[i-1][0]);
NODE *tmp;
NODE *out = freqCheck(argv[i], tmp);
write(p[i-1][1], out, sizeof(NODE));
exit(0);
}
}
if (pid > 0){
//parent process
int j;
for (j = 0; j < argc-1; j++)
{
close(p[j][1]);
NODE *tmp;
read(p[j][0], tmp, sizeof(NODE));
printf("%s\n", tmp->word);
}
}
When the parent process attempts to read from the pipe and interpret one of the attributes of the structure, I just get null values back.
I’m using an array of 2 element integer arrays to keep track of each child processes’ pipe. The printf statement above returns null revery time.
Any idea what I’m doing wrong?
Code for the FrqCheck method:
//Method for determining the most occuring word
NODE * freqCheck(char *file, NODE *max)
{
int i;
FILE *f;
char str[128];
//Set up head and tail nodes
NODE *head = NULL;
NODE *tail = NULL;
if ((f = fopen(file, "r")) == NULL)
{
//sprintf(output, "%s could not be opened.", file);
}else
{
//scan each word of the input file
while(fscanf(f, "%s ", str) != EOF)
{
//if the linked-list has no nodes, create one
if (head == NULL)
{
NODE *n;
n = (NODE *)malloc(sizeof(NODE));
strcpy(n->word, str);
n->frequency = 1;
n->next = NULL;
head = n;
tail = n;
}else{ //search the linked list for the found word.
NODE *current = head;
int found = 0;
while((current != NULL) && (found == 0))
{
//if the word is found increment the frequency
if (strcmp(current->word, str) == 0)
{
current->frequency ++;
found = 1;
}else
{
current = current->next;
}
}
//if the word is not found, create a node and add to the liked-list
if (found == 0)
{
NODE *new;
new = (NODE *)malloc(sizeof(NODE));
strcpy(new->word, str);
new->frequency = 1;
new->next = NULL;
tail->next = new;
tail = new;
}
}
}
//traverse the linked-list and find the word with the maximum frequency
NODE *tmp = head;
max = tmp;
while (tmp != NULL)
{
if (tmp->frequency > max->frequency)
{
max = tmp;
}else
{
tmp = tmp->next;
}
}
//sprintf(output, "%s %s %d", file, max->word, max->frequency);
}
//printf("%s\n", max->word);
return max;
}
Where are you allocating storage for your
NODEstructures? DoesfreqCheckallocate storage? In the parent process, when you callread()and thenprintf, you pass in an uninitializedNODEpointer, so of course you’re getting undefined behavior.