问题描述
我似乎找不到通过命名管道发送 int 的任何解释,尽管我见过很多类似的事情。 现在,该程序接受用户输入的 Collatz 猜想,但它退出时好像输入为 0。 父进程接收输入并将其发送给子进程。
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int pid;
int fd[2];
int input;
//create child
pid = fork();
if (pid > 0){
//parent process
wait(NULL);
close(fd[0]);
std::cout << "Enter an int value: ";
std::cin >> input;
write(fd[1],&input,sizeof(input));
close(fd[1]);
}
else if (pid == 0){
close(fd[1]);
//child process
read(fd[0],sizeof(input));
int workingNum = input;
close(fd[0]);
if (workingNum > 0){
while (workingNum != 1){
//even
if(workingNum % 2 == 0){
workingNum = workingNum / 2;
std::cout << workingNum;
std::cout << " ";
}
else {
workingNum = 3 * workingNum + 1;
std::cout << workingNum;
std::cout << " ";
}
}
}
}
return 0;
}
解决方法
两个错误:
-
正如 jtbandes 指出的,您必须实际调用
pipe(2)
函数来创建管道。pipe(fd)
之前的fork()
也是如此。 (带有-Wall -O
的 g++ 会警告您fd
未初始化。) -
您有一个典型的死锁:父进程调用
wait(NULL)
,因此在子进程退出之前它不会继续写入管道。但是孩子正在尝试从管道中读取,并且在父母写了一些东西之前不会继续退出。所以这两个过程都卡住了。您可能希望将wait(NULL)
移到父代码的末尾。
经过这些更改后,它对我有用。但是,对所有系统调用进行错误检查会很好。