gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
编写一个程序,建立一个管道。父进程生成两个子进程,p1和p2,两个子进程分别向管道中写入各自的字符串,父进程读出它们。(p1写:child process…
- User
编写一个程序,建立一个管道。父进程生成两个子进程,p1和p2,两个子进程分别向管道中写入各自的字符串,父进程读出它们。(p1写:child process P1,p2写:child process P2)
- Assistant
以下是一个满足要求的C代码示例:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #define BUFFER_SIZE 50 int main() { int pipefd[2]; pid_t p1, p2; char buff_p1[] = "child process P1\n"; char buff_p2[] = "child process P2\n"; char readBuffer[BUFFER_SIZE]; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } // 创建子进程p1 p1 = fork(); if (p1 == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (p1 == 0) { close(pipefd[0]); // 关闭读端 write(pipefd[1], buff_p1, strlen(buff_p1)); exit(EXIT_SUCCESS); } // 创建子进程p2 p2 = fork(); if (p2 == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (p2 == 0) { close(pipefd[0]); // 关闭读端 write(pipefd[1], buff_p2, strlen(buff_p2)); exit(EXIT_SUCCESS); } // 父进程 close(pipefd[1]); // 关闭写端 wait(NULL); // 等待子进程结束 while (read(pipefd[0], readBuffer, BUFFER_SIZE) > 0) { printf("Parent process receives: %s", readBuffer); } close(pipefd[0]); return 0; }该程序首先创建了一个管道,接着创建了两个子进程p1和p2。子进程p1和p2分别关闭管道的读端,向写端写入各自的字符串("child process P1"和"child process P2")。父进程关闭管道的写端,等待子进程结束,不断从读端读取数据并输出,直到读到空数据。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.