You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

并发素数筛程序中read()调用返回-1的问题排查

并发素数筛程序调试问题

我正在实现一个并发素数筛程序,核心逻辑是每个管道负责剔除当前数字的倍数:第一个管道剔除所有2的倍数,将非倍数发送到下一个管道;下一个管道再剔除所有3的倍数,以此类推。

我的实现代码如下:

void receiveAndSend(int wr[35][2], int pipeNr) {
    int p;
    if (close(wr[pipeNr][1]) < 0) {
        perror("close 1");
    }
    if (read(wr[pipeNr][0], &p, 4) < 0) {
        perror("Read1");
    }
    
    printf("prime %d, from file descriptor %d\n", p, wr[pipeNr][0]);
    int j;
    pipeNr++;
    pipe(wr[pipeNr]);
    int cont = 0; 
    
    // enclose all of this in new fork
    int sec = fork();
    if (sec == 0) {
        //close(wr[pipeNr][0]);
        while (read(wr[pipeNr - 1][0], &j, 4) > 0) {
            if (j % p != 0) {
                // printf("%d is not divisible by %d\n", j, p);
                cont = 1;
                if (write(wr[pipeNr][1], &j, 4) < 0) {
                    perror("Write x");
                }
                // perror("test");
            }   
        }       
                    
        if (close(wr[pipeNr - 1][0]) < 0) {
            perror("close x");
        }
        // perror("test2");
        
        if (cont) {
            // printf("arrived\n");
            receiveAndSend(wr, pipeNr);
        }
        exit(0);
    }   
    if (wait(0) < 0) {
        perror("Wait Outter");
    }       
}

遇到的问题

  • 第6行的read调用:首次执行函数时正常返回4,但首次递归调用后返回-1。
  • 初始文件描述符wr[0]中已填充2到35的数字,系统有35个可用文件描述符(不会全部用到)。
  • 第23行向后续管道的写入操作正常,每次迭代返回4。
  • 怀疑问题出在子进程或文件描述符关闭操作上,但尝试多种组合仍未解决。

更新进展

在Linux机器上调试并打印errno后,程序能完成第二次迭代,输出如下:

prime 2, from file descriptor 3
prime 3, from file descriptor 4

但之后程序挂起,errno显示为“Success”。写入操作和while循环均正常,但循环结束后程序莫名挂起,无报错信息。

内容的提问来源于stack exchange,提问作者a6i09per5f

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:42:44