下面代码运行为啥没结果

下面代码运行为啥没结果

img


#include 
#include 
#include 
#include 
#include 
#include 

#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;
}

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

// 在子进程中
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了。