c - 使用管道,从父进程读取 2 个数字,子进程计算它们的总和并将结果提供给父进程进行打印

标签 c linux pipe

我是 C 和 linux 系统编程的新手。 我为父进程和子进程之间的双向通信创建了 2 个管道。我正在阅读 parent 的数字,例如:

1 2(enter)

(enter) 表示按回车进入新行。 使用管道,我将此输入发送到子进程,我想计算这些数字的总和。然后使用另一个管道,我将总和发送回父级进行打印。 当我运行代码时,输​​出不显示。是这样的:

./a.out
2 3
hamzasidiki@Hamza-PC:~/Desktop/SPMukhi/New$ 

如您所见,程序并未打印结果并在之前结束。我的代码有什么问题?任何帮助表示赞赏。 TIA。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
int fd1[2];
int fd2[2];
pid_t cpid;
int wstatus;

pipe(fd1);
pipe(fd2);

cpid = fork();
if(cpid == -1) {
    perror("fork");
    exit(0);
}
if(cpid > 0) {
    //Parent
    int rc;
    char pbuff[20];
    int rcp1 = read(STDIN_FILENO, pbuff, 20);

    close(fd1[0]);
    write(fd1[1], pbuff, rcp1);
    close(fd1[1]);
    waitpid(cpid, wstatus, 0);
    close(fd2[1]);
    char pbuff1[20];
    int rcp2 = read(fd2[0], pbuff1, 20);

    pbuff1[rcp2 - 1] = '\0';
    close(fd2[0]);
    write(STDOUT_FILENO, pbuff1, rcp2);

}
if(cpid == 0) {
    //Child
    int sum = 0;
    char cbuff[20];
    close(fd1[1]);
    int rcc = read(fd1[0], cbuff, 20);

    cbuff[rcc - 1] = '\0';
    char *a = strtok(cbuff, " ");
    while(a != NULL) {
        int a = atoi(a);
        sum += a;
        a = strtok(NULL, " ");
    }
    close(fd1[0]);
    close(fd2[0]);
    char w[20];
    int n = sprintf(w, "Result = %d\n", sum);
    write(fd2[1], w, n);
    close(fd2[1]);



       }

           }

最佳答案

清除编译器给我的警告后,它对我有用。

  • 在子代码的 while 循环中为整数 a 使用不同的变量名。它混淆了 atoi() 函数调用。
  • waitpid() 期望在您提供整数的第二个参数中有一个指针。传递 &wstatus 或仅传递 NULL 因为您无论如何都不会使用状态。

关于c - 使用管道,从父进程读取 2 个数字,子进程计算它们的总和并将结果提供给父进程进行打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132568/

相关文章:

c - 切换到C编程

windows - 在 Windows 中仅命名带扩展名的文件

objective-c - 适用于 Linux 的 Apple iOS IDE?

powershell - 如何获得管道对象的数量?我不想累积管道来缓冲

WinAPI C++ 客户端在读取之前检测匿名管道上的写入

c - 使用 malloc 给我的内存比预期的多吗?

c - 内存困惑

python - 与 C 程序通信时,子进程 Popen 无效参数/损坏的管道

c - 缓存的 SSL session 是否包含以前的 X.509 证书信息?

Linux Kernel 4.7 (Arch ARM64) 不在/sys/bus/pci/devices/*/中为 PCI BAR0 创建 "resource0"文件