#elif FORKSERVER /* * TODO: PART 5 * * When a client connection has been accepted, a new…
- User
#elif FORKSERVER /* * TODO: PART 5 * * When a client connection has been accepted, a new * process is spawned. This child process will send * a response to the client. Afterwards, the child * process should exit. During this time, the parent * process should continue listening and accepting * connections. */
code/* PART 5 BEGIN */ /* PART 5 END */完成代码 - Assistant
#elif FORKSERVER /* * TODO: PART 5 * * When a client connection has been accepted, a new * process is spawned. This child process will send * a response to the client. Afterwards, the child * process should exit. During this time, the parent * process should continue listening and accepting * connections. */
code/* PART 5 BEGIN */ // Create a child process pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (pid == 0) { // Child process code // Close the listening socket in the child process close(listenfd); // Send response to the client char response[] = "Hello, client!"; if (send(connfd, response, sizeof(response), 0) == -1) { perror("send"); exit(EXIT_FAILURE); } // Close the connection socket in the child process close(connfd); // Exit the child process exit(EXIT_SUCCESS); } else { // Parent process code // Close the connection socket in the parent process close(connfd); } /* PART 5 END */完成代码 - User
请解释代码
- Assistant
该代码使用了 fork() 函数创建了一个子进程。当一个客户端连接被接受时,父进程会创建一个子进程来处理该连接。子进程会发送响应给客户端,然后退出。而父进程会继续监听和接受连接。
在子进程中,首先关闭了监听套接字(listenfd),然后使用 send() 函数将响应发送给客户端。如果发送失败,会输出错误信息并退出子进程。之后,关闭连接套接字(connfd),并退出子进程。
在父进程中,关闭了连接套接字(connfd),以便继续监听和接受其他连接。