Reputation: 11
I can't seem to find any explanation for sending an int through a named pipe, although I've seen many similar things. Right now the program takes user input for a Collatz conjecture, but it exits as if the input if 0. The parent process takes in input and sends it to a child process.
#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], &input, 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;
}
Upvotes: 1
Views: 427
Reputation: 58142
Two bugs:
As jtbandes points out, you have to actually call the pipe(2)
function to create a pipe. So do pipe(fd)
before the fork()
. (g++ with -Wall -O
will give you a warning about fd
being uninitialized.)
You have a classic deadlock: the parent calls wait(NULL)
so it won't continue on to write to the pipe until the child has exited. But the child is trying to read from the pipe and won't continue on to exit until the parent has written something. So both processes remain stuck. You probably want to move the wait(NULL)
to the end of the parent's code.
After those changes it works for me. Error checking on all the system calls would be nice, however.
Upvotes: 1