酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C语言:用管道实现Linux进程间通信,父写子读示例

以下是一个使用管道在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); } } ``` 这个程序首先创建一个管道,然后创建一个子进程。父进程向管道写入数据,子进程从管道中读取数据并打印出来。 ######[AI写代码神器 | 372点数解答 | 2024-05-30 10:32:36]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]