下面代码运行为啥没结果
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUF_SIZE 256 // 管道的缓冲区大小
// 信号处理函数
void signal_handler(int signal)
{
// 什么都不做
}
// 从管道中读取数据
int read_from_pipe(int pipefd[])
{
// 定义缓冲区
char buf[BUF_SIZE];
// 从管道中读取数据
int bytes_read = read(pipefd[0], buf, BUF_SIZE);
if (bytes_read == -1)
{
perror("read failed");
return -1;
}
// 返回读取到的整型数据
return atoi(buf);
}
// 向管道中写入数据
int write_to_pipe(int pipefd[], int data)
{
// 将整型数据转换为字符串
char buf[BUF_SIZE];
sprintf(buf, "%d", data);
// 向管道中写入数据
int bytes_written = write(pipefd[1], buf, BUF_SIZE);
if (bytes_written == -1)
{
perror("write failed");
return -1;
}
return 0;
}
int main()
{
// 定义管道
int pipefd[2];
// 创建管道
if (pipe(pipefd) == -1)
{
perror("pipe failed");
return 1;
}
// 创建子进程
pid_t pid = fork();
if (pid == -1)
{
perror("fork failed");
return 1;
}
// 在父进程中
if (pid > 0)
{
// 关闭读端
close(pipefd[0]);
// 设置信号处理函数
signal(SIGUSR1, signal_handler);
// 不断循环
while (1)
{
// 等待信号
pause();
// 写入数据
write_to_pipe(pipefd, 1);
}
}
// 在子进程中
// 在子进程中
else
{
// 关闭写端
close(pipefd[1]);
// 设置信号处理函数
signal(SIGUSR2, signal_handler);
// 不断循环
while (1)
{
// 等待信号
pause();
// 读取数据
int data = read_from_pipe(pipefd);
// 将数据写到终端
printf("%d\n", data);
// 发送信号
kill(getppid(), SIGUSR1);
}
// 关闭管道
close(pipefd[0]);
}
return 0;
}