yjhklxx 2022-12-11 12:08 采纳率: 0%
浏览 51

下面代码运行为啥没结果

下面代码运行为啥没结果

img


#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;
}
  • 写回答

1条回答 默认 最新

  • 无终无了 2022-12-11 15:48
    关注

    上面的代码没有结果,是因为在子进程中,没有发送信号给父进程,父进程无法写入数据。我们可以在子进程中,在读取数据之后,发送信号给父进程,通知父进程可以写入数据。代码如下:

    // 在子进程中
    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]);
    

    }

    修改之后,代码就可以正常运行,并输出连续的1了。

    评论

报告相同问题?

问题事件

  • 创建了问题 12月11日

悬赏问题

  • ¥50 C++使用TWAIN协议如何实现A3幅面扫描仪扫描A4横向
  • ¥15 如何在sql server里完成筛选
  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题