linked list elements gone?
        Posted  
        
            by Hristo 
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Hristo 
        
        
        
        Published on 2010-04-07T21:55:08Z
        Indexed on 
            2010/04/07
            22:03 UTC
        
        
        Read the original article
        Hit count: 359
        
I create a linked list dynamically and initialize the first node in main(), and I add to the list every time I spawn a worker process. Before the worker process exits, I print the list. Also, I print the list inside my sigchld signal handler.
in main():
head = NULL;
tail = NULL;
// linked list to keep track of worker process
dll_node_t *node;
node = (dll_node_t *) malloc(sizeof(dll_node_t)); // initialize list, allocate memory
append_node(node);
node->pid = mainPID; // the first node is the MAIN process
node->type = MAIN;
in a fork()'d process:
    // add to list
    dll_node_t *node;
    node = (dll_node_t *) malloc(sizeof(dll_node_t));
    append_node(node);
    node->pid = mmapFileWorkerStats->childPID;
    node->workerFileName = mmapFileWorkerStats->workerFileName;
    node->type = WORK;
functions:
void append_node(dll_node_t *nodeToAppend) {
    /*
     * append param node to end of list
     */
    // if the list is empty
    if (head == NULL) {
        // create the first/head node
        head = nodeToAppend;
        nodeToAppend->prev = NULL;
    } else {
        tail->next = nodeToAppend;
        nodeToAppend->prev = tail;
    }
    // fix the tail to point to the new node
    tail = nodeToAppend;
    nodeToAppend->next = NULL;
}
finally... the signal handler:
void chld_signalHandler() {
    dll_node_t *temp1 = head;
    while (temp1 != NULL) {
        printf("2. node's pid: %d\n", temp1->pid);
        temp1 = temp1->next;
    }
    int termChildPID = waitpid(-1, NULL, WNOHANG);
    dll_node_t *temp = head;
    while (temp != NULL) {
        if (temp->pid == termChildPID) {
            printf("found process: %d\n", temp->pid);
        }
        temp = temp->next;
    }
    return;
}
Is it true that upon the worker process exiting, the SIGCHLD signal handler is triggered? If so, that would mean that after I print the tree before exiting, the next thing I do is in the signal handler which is print the tree... which would mean i would print the tree twice?
But the tree isn't the same. The node I add in the worker process doesn't exist when I print in the signal handler or at the very end of main(). Any idea why?
Thanks, Hristo
© Stack Overflow or respective owner