我已經在C中實現了一個基本鏈接列表,作爲項目的一部分來開發一個簡單的shell - 它支持通過維護shell在其中運行的pid列表來支持進程的後臺背景。代碼如下。使用queue_process(some_pid)
插入時第一次正常工作,但隨後鏈接列表的行爲就好像列表中沒有任何節點(即「無現有進程」總是由調試功能打印)。我已經檢查過這個文件和調用這些函數的文件,以便將頭指針重置爲無效。我在鏈接列表邏輯中遺漏了什麼?C中丟失頭信息的鏈接列表
到queue_process編輯電話:發生在由shell啓動的子進程,看起來像這樣/編輯:queue_process(getpid())
謝謝!
void queue_process(pid_t pid_to_insert)
{
pmesg(2, "In queue_process.\n");
if (head == NULL)
{
pmesg(3, "No existing processes.\n");
head = malloc(sizeof(struct xssh_process));
head->pid = pid_to_insert;
head->next = NULL;
}
else
{
pmesg(3, "There are existing processes.\n");
struct xssh_process *new_process = malloc(sizeof(struct xssh_process));
new_process->next= head;
head = new_process;
}
print_processes();
}
void print_processes()
{
pmesg(2, "In print_processes.\n");
struct xssh_process *at_node = head;
if (head == NULL) { pmesg(2, "There are currently no background processes.\n"); return; }
pmesg(2, "Process IDs from head (most recently executed) to tail: %i -> ", at_node->pid);
while (at_node != NULL)
{
pmesg(2, "%i ->", at_node->pid);
at_node = at_node->next;
}
pmesg(3, "Head's pid in print is %i.\n", head->pid);
}
查找鏈表的不同實現會更好嗎?這個代碼或者總體程序似乎有某種固有的缺陷。 – 2011-02-01 06:20:53
什麼是「struct xssh_process」的聲明?它是一個完整的結構或只是一個標籤?在編寫鏈表時,您可能首先使用了一個不完整的struct標籤,以使節點能夠指向自己。 – Lundin 2011-02-01 14:40:09