我試圖寫組成的字符數組,一個整數值,並且一個指向管的結構寫入結構的管。該結構表示單鏈表中的節點。閱讀和用C
//Define a linked-list node object
typedef struct node{
char word[128];
int frequency;
struct node *next;
} NODE;
該程序的目標是使用管道將節點從幾個併發的子進程傳遞給父進程。我已經實現的管道結構似乎可以正常使用字符數組,但如果我嘗試傳遞整個節點對象,則不起作用。
//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);
}
}
當父進程試圖從管道讀取和解釋結構的屬性之一,我只是得到空值回來。
我使用2個元件整數數組的數組跟蹤每個子進程管。上面的printf語句返回null返回時間。
任何想法我做錯了什麼?
代碼爲FrqCheck方法:
//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;
}
是頻率檢查構造鏈表併爲每個節點分配內存。該方法掃描文件中的單詞,並確定哪個單詞出現最多。它返回一個節點實例。 – isometrik 2011-01-27 23:35:29
但是... show source ... – Svisstack 2011-01-27 23:36:06