gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
用c语言写一个用中断通信的函数
- User
用c语言写一个用中断通信的函数
- Assistant
下面是一个使用中断通信的示例代码,实现了两个进程之间的通信:
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> volatile sig_atomic_t flag = 0; void handler(int sig) { flag = 1; // 设置标志位,表示收到中断信号 } void int_communication() { pid_t pid; int pipefd[2]; // 创建管道 if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } // 创建子进程 pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { // 子进程 sleep(1); // 等待父进程初始化 printf("子进程开始发送消息...\n"); close(pipefd[0]); // 关闭读端 char msg[] = "Hello, parent process!"; write(pipefd[1], msg, sizeof(msg)); printf("子进程发送消息完毕\n"); close(pipefd[1]); // 关闭写端 exit(EXIT_SUCCESS); } else { // 父进程 signal(SIGINT, handler); printf("父进程等待中断信号...\n"); while (!flag) { sleep(1); } printf("父进程收到中断信号\n"); close(pipefd[1]); // 关闭写端 char buffer[100]; read(pipefd[0], buffer, sizeof(buffer)); printf("父进程收到消息: %s\n", buffer); close(pipefd[0]); // 关闭读端 exit(EXIT_SUCCESS); } } int main() { int_communication(); return 0; }