STEP #1

(1/2)

此处切换ai服务商,可对比多家ai的回复,取最优解。

上一步下一步关闭
酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

请编写一个c语言程序,使用管道(pipe)在linux进程间通信(ipc)。实现父进程会创建一个管道,并启动一个子进程。父进程会向管道写入一些数据,子进程会从管道中读取这些数据

以下是一个使用管道在Linux进程间通信的C语言程序示例: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { int pipefd[2]; pid_t pid; char buf[1024]; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { // 子进程 close(pipefd[1]); // 关闭写端 read(pipefd[0], buf, sizeof(buf)); printf("子进程接收到的数据: %s ", buf); close(pipefd[0]); exit(EXIT_SUCCESS); } else { // 父进程 close(pipefd[0]); // 关闭读端 write(pipefd[1], "Hello, 子进程!", 16); close(pipefd[1]); wait(NULL); // 等待子进程结束 exit(EXIT_SUCCESS); } } ``` 这个程序首先创建一个管道,然后创建一个子进程。父进程向管道写入数据,子进程从管道中读取数据并打印出来。 [2024-05-30 10:32:36 | AI写代码神器 | 372点数解答]

相关提问