简体   繁体   中英

Why can not break out of the while loop in which many child threads are forked?

In my program, each time the user types a message via stdin, the code reads it in, and calls fork() to create a new (child) process. This child process sends data (the user's typed in message) using a server socket.

To end the client process, I would like the user to type "quit". At which point, I would like my code to exit the While(1) loop, wait for all the child processes to finish processing (so leaving behind no orphaned/zombie processes). And then at this point, when all the child processes have finished and exited, I would like the program to end.

However now and with my code as shown below, when the user types "quit", although the child processes terminate successfully, the loop starts over. Does any one know what am I doing wrong in the code?

int status = 0;
while (1) {

    // Read request from standard input
    printf("Enter a message: ");
    memset(out_buffer, 0, BUFFER_SIZE);
    fgets(out_buffer, BUFFER_SIZE - 1, stdin);
    out_buffer[strcspn(out_buffer, "\r\n")] = 0;

    // Spawn new process to handle new client
    if ((pid = fork()) == -1) {
        printf("[-]Error spawning child process for new client.\n");
        continue;
    }
    // Child process
    else if (pid == 0) {
        // ...
        if (input_status == -2) {
            printf("[-]Disconnected from server.\n");
            close(socket_fd);
            termination_call = 1;
            exit(0);
        }
    }

    if (termination_call == 1) {
        printf("[-]Client terminating...\n");
        break;
    }

}

// Wait for all child processes to exit
while ((wpid = wait(&status)) > 0);
return 0;

You need to check for the "quit" command in the parent .

When you fork a new process, it runs independent of the parent process, and no data is shared between them.

If you want to share data then consider threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM