为何程序通过命名管道传递值却输出内存地址而非目标值?
命名管道在父子进程间传递数值时的无效结果问题
我在使用命名管道实现父子进程间数值传递时遇到问题,测试传入值22,却持续得到类似整数内存地址的无效结果。以下是我的C语言代码及运行输出:
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> void fib(int n) { int fib1; int fib2; int fd; int sum; char * myfifo = "/home/user/Desktop"; mkfifo("myfifo", 0666); if (mkfifo("myfifo", 0666) < 0 && errno != EEXIST) { perror("mkfifo failure"); exit(1); } if ((fd = open("myfifo", O_WRONLY)) < 0) { perror("open failure"); exit(2); } if (n == 0 || n == 1) { fib1 = 22; write(fd, &fib1, sizeof(fib1)); // write fib(n) into the pipe/shared memory/shared queue close(fd); return; } else { int pid = fork(); if (pid == 0) { // child fib(n - 1); exit(0); } else { waitpid(pid, NULL, 0); // parent fib(n - 2); read(fd, &fib1, sizeof(fib1)); // read fib(n - 1) & fib(n - 2) from the pipe/shared memory/shared queue read(fd, &fib2, sizeof(fib2)); // read fib(n - 1) & fib(n - 2) from the pipe/shared memory/shared queue printf("Value 1: %d\n", fib1); printf("Value 2: %d\n", fib2); sum = fib1 + fib2; printf("Sum: %d\n", sum); write(fd, &sum, sizeof(sum)); // write fib(n) back into the pipe/shared memory/shared queue } return; } printf("Sum: %d", sum); } int main() { int value; printf("Enter number to be calculated: "); scanf("%d", &value); fib(value); return 0; }
运行输出:
Enter number to be calculated: 3 Value 1: -140833897 Value 2: 0 Sum: -140833897 Value 1: 0 Value 2: 0 Sum: 0
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

