使用无名管道进行父子进程之间的通信,父进程发送给子进程接收,当发送了quit就退出

本文介绍了如何在C/C++中利用无名管道实现父子进程间的通信。父进程向子进程发送数据,当接收到'quit'信号时,父进程终止通信并退出。
摘要由CSDN通过智能技术生成

练习:使用无名管道进行父子进程之间的通信,父进程发送给子进程接收,当发送了quit就退出

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>

//使用无名管道进行父子进程之间的通信࿰
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现子进程之间的轮流通信,可以使用管道(pipe)来进行进程间的通信。下面是一个示例代码,演示了进程子进程之间轮流发送消息的过程: ```c #include <stdio.h> #include <unistd.h> #include <string.h> #define BUFFER_SIZE 100 int main() { int pipe_fd[2]; char buffer[BUFFER_SIZE]; if (pipe(pipe_fd) == -1) { perror("Failed to create pipe"); return 1; } pid_t pid = fork(); if (pid == -1) { perror("Failed to create child process"); return 1; } if (pid == 0) { // Child process close(pipe_fd[1]); // 关闭写端 while (1) { memset(buffer, 0, sizeof(buffer)); ssize_t count = read(pipe_fd[0], buffer, BUFFER_SIZE); if (count == -1) { perror("Failed to read from pipe"); break; } printf("Child process received: %s\n", buffer); if (strcmp(buffer, "quit") == 0) { break; } } close(pipe_fd[0]); // 关闭读端 } else { // Parent process close(pipe_fd[0]); // 关闭读端 while (1) { printf("Enter message (quit to exit): "); fgets(buffer, BUFFER_SIZE, stdin); buffer[strlen(buffer) - 1] = '\0'; // 去掉末尾的换行符 ssize_t count = write(pipe_fd[1], buffer, strlen(buffer)); if (count == -1) { perror("Failed to write to pipe"); break; } if (strcmp(buffer, "quit") == 0) { break; } } close(pipe_fd[1]); // 关闭写端 } return 0; } ``` 在上面的代码中,首先创建了一个管道pipe_fd,然后通过fork()函数创建子进程。在进程中,关闭了管道的读端,然后进入一个循环,等待用户输入消息进程通过write()函数将用户输入的消息写入管道。如果用户输入的消息为"quit",则终止循环并关闭管道的写端。 在子进程中,关闭了管道的写端,然后进入一个循环,通过read()函数读取进程发送消息。如果收到的消息为"quit",则终止循环并关闭管道的读端。 需要注意的是,子进程之间通信是通过管道实现的,写端和读端必须在合适的时候关闭,以确保通信的正确性。另外,在实际应用中,还需要考虑进程间同步和错误处理等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值