簡體   English   中英

為什么不能中斷分支很多子線程的while循環?

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

在我的程序中,每次用戶通過stdin鍵入一條消息時,代碼都會讀入該消息,然后調用fork()創建一個新的(子)進程。 該子進程使用服務器套接字發送數據(用戶輸入的消息)。

為了結束客戶端進程,我希望用戶鍵入“ quit”。 在這一點上,我希望我的代碼退出While(1)循環,等待所有子進程完成處理(因此不留下任何孤立/僵屍進程)。 然后在這一點上,當所有子進程都已完成並退出時,我希望程序結束。

但是現在,使用我的代碼,如下所示,當用戶鍵入“ quit”時,盡管子進程成功終止,循環仍會重新開始。 有誰知道我在代碼中做錯了什么嗎?

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;

您需要在parent中檢查"quit"命令。

派生新進程時,它獨立於父進程運行,並且它們之間沒有共享數據。

如果要共享數據,請考慮使用線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM