I'm trying to send numbers from a file to child processes with fork() and pipe(), which the child processes should add and send back to the parent process which will then add the child sums to get a total sum.
For a simplified version of that problem, I've got an Array of 4 numbers, and am only using 1 Child process (2 pipes).
I'm having difficulties seeing where control in my program goes, which makes it hard for me to troubleshoot what else is going wrong.
int main(int argc, char *argv[])
{
int numChildProcesses = 1;
int testArray[4] = {2,7,9,4};
printf("Will use 1 child process; %d pipes.\n", numChildProcesses*2);
int fd[numChildProcesses*2][2]; //parent and child
int val = 0, len, i;
// create all the descriptor pairs we need
for (i=0; i<numChildProcesses*2; ++i) // 2 pipes // parent + child
{
if (pipe(fd[i]) < 0)
{
perror("Failed to allocate pipes.");
exit(EXIT_FAILURE);
}
}
for (i=0;i<numChildProcesses;i++)
{
//CHILD/////////////////////////////////////////////////////////////////////
if (fork() == 0)
{
int total = 0, xCount = 0;
while (xCount < 4)
{
// wait for parent to send us a value
len = read(fd[i][0], &val, sizeof(val));
if (len < 0)
{
perror("Child: Failed to read data from pipe.\n");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
// not an error, but certainly unexpected
fprintf(stderr, "Child: Read EOF from pipe\n");
}
else // Successfully read from Parent
{
total += val;
xCount += 1;
printf("Child: Recieved %d\tTotal: %d\tCount: %d\n", val, total, xCount);
}
}
// send the value back to the parent
printf("Child: Sending %d back\n", total);
if (write(fd[i][1], &total, sizeof(total)) < 0)
{
perror("Child: Failed to write response value");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
//PARENT/////////////////////////////////////////////////////////////////////
if (fork() > 0)
{
int total = 0;
// send array to child as well as starting point
printf("\nParent: Sending numbers to child\n");
//if (write(fd[i][1], 0, (fileNumbers/numChildProcesses)*5) != sizeof((fileNumbers/numChildProcesses)*5));
if (write(fd[i][1], &testArray, sizeof(testArray)) != sizeof(testArray))
{
perror("Parent: Failed to send value to child ");
exit(EXIT_FAILURE);
}
// now wait for a response
len = read(fd[i][0], &val, sizeof(val));
if (len < 0)
{
perror("Parent: failed to read value from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
// not an error, but certainly unexpected
fprintf(stderr, "Parent: Read EOF from pipe\n");
}
else
{
// report what we received
total += val;
printf("Parent: Received %d\tTotal: %d\n", val, total);
}
// wait for child termination
wait(NULL);
}
}
}
My output is as follows:
Will use 1 child process; 2 pipes.
Parent: Sending numbers to child
Parent: Received 2 Total: 2
Child: Recieved 7 Total: 7 Count: 1
Child: Recieved 9 Total: 16 Count: 2
Child: Recieved 4 Total: 20 Count: 3
Furthermore, if I try something like printf("%d", fork()); as soon as I enter my for() loop to see what it taking control, it gets a little crazy. It acts like using fork() affects the way the program runs, as if it is a pop() or something of the sort.
Anyways, thank you for any insight you can offer.
-Tom
You're forking too much. You're calling fork() twice in your loop: once in your "child" if, and one in your "parent" if. And then even more when you add your printf("%d", fork());.
You should only call fork() once per loop. Save the return value in a variable, then print/check it.
Related
I have a program that creates a child process from a fork() call. The child will continuously receive 1-byte integer input from the user. Once an integer has been sent to the child, the child will send the value to the parent using a pipe. When the parent receives the value, it will add it to an array. -1 is sent to end the program. Once the child sends the parent -1, the parent will sum the previous values in the array and, using another pipe, send this sum value to the child in which the child will print it and terminate the program.
As of right now this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
//Gets input from the user
int getInput() {
int val; char temp;
scanf("%hhd", &temp);
val = temp;
return val;
}
//Sums the values of the entered numbers and returns it
int finish(int arr[], int i) {
int sum = 0;
for (int j = 0; j < i; j++) {sum+= arr[j];}
return(sum);
}
int main() {
int fd[2], fd2[2], val = 0, i = 0, sum, final = -9999999;
int arr[1000];
pid_t pidVal;
//Pipe for sending numbers from child to parent
pipe(fd);
//Pipe for sending the final sum from parent to child
pipe(fd2);
//Create parent and child processes
pidVal = fork();
//Used to make it run continously until -1 is pressed
while(1) {
//Child Process
if (pidVal == 0) {
printf("Child Process (should be 0): %d\n", pidVal);
val = getInput();
printf("You typed: %d\n", val);
//Write to parent
close(fd[0]);
write(fd[1], &val, sizeof(val));
//Read if parent sends sum yet
close(fd2[1]);
read(fd2[0], &final, sizeof(final));
//If sum sent from parent, print and terminate
if (final != -9999999) {
printf("%d\n", final);
exit(0);
}
}
//Parent Process
if (pidVal > 0) {
printf("I'm the parent (should be > 0): %d\n", pidVal);
//Read what child sent to the pipe
close(fd[1]);
read(fd[0], &val, sizeof(val));
//If exit value recieved
if (val == -1) {
//Sum the numbers sent
sum = finish(arr, i);
//Close read directory
close(fd2[0]);
//Write the sum to the pipe
write(fd2[1], &sum, sizeof(sum));
}
//Not -1 as input
else {
//Collect input
arr[i] = val;
i++;
}
}
}
}
However the problem is when I try and send more than one number, the program is stuck, as you can see from this sample output:
I'm the parent (should be > 0): 5673
Child Process (should be 0): 0
3 //My Input
You typed: 3
I'm the parent (should be > 0): 5673
1 //My Input
2 //My Input
I noticed how the child process does not seem to execute at the second iteration, yet the parent does, which leads me to believe the child is terminating after the first run. How can I keep this child alive until the user enters -1? More importantly I want to achieve this functionality with only one parent and one child process derived from only a single fork call for the entire program. Is this possible?
In your child section:
while(1) {
if (pidVal == 0) {
printf("Child Process (should be 0): %d\n", pidVal);
val = getInput();
printf("You typed: %d\n", val);
//Write to parent
close(fd[0]);
write(fd[1], &val, sizeof(val));
//Read if parent sends sum yet
close(fd2[1]);
read(fd2[0], &final, sizeof(final));
//If sum sent from parent, print and terminate
if (final != -9999999) {
printf("%d\n", final);
exit(0);
}
}
...
You're reading a single value from the user, sending it to the parent, then waiting for the result from the parent. The parent meanwhile has read the first value from the child and is waiting for another value, so the parent and child are deadlocked waiting for the other to send them something.
You want the child to loop reading values until it gets -1, then wait for the parent.
if (pidVal == 0) {
printf("Child Process (should be 0): %d\n", pidVal);
do {
val = getInput();
printf("You typed: %d\n", val);
//Write to parent
close(fd[0]);
write(fd[1], &val, sizeof(val));
} while (val != -1);
close(fd2[1]);
read(fd2[0], &final, sizeof(final));
//If sum sent from parent, print and terminate
if (final != -9999999) {
printf("%d\n", final);
exit(0);
}
}
Here is what I am trying to do:
Write a C program that takes an integer command line argument n,
spawns n processes that will each generate a random numbers between
-100 and 100, and then computes and prints out the sum of these random numbers. Each process needs to print out the random number it
generates.
This is what I have so far:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int command,processCheck; // processCheck: to check if fork was successful or not and to
char * strNumProcess = NULL;// check the status of child process
while((command = getopt(argc, argv, "n:"))!=-1){
if(command == 'n'){
strNumProcess = optarg;
break;
}
}
int numProcess = atoi(strNumProcess);
int pipes[numProcess][2];
int randomNum; // Variable to store the random number
int randomNumSum=0; // Initialized variable to store the sum of random number
/** A loop that creates specified number of processes**/
for(int i=0; i<numProcess; i++){
processCheck = fork(); // creates a child process. Usually fork() = 2^n processes
if(processCheck < 0){ // Checks for the error in fork()
printf("Error");
exit(1); // Terminates with error
}
else if(processCheck == 0){
close(pipes[i][0]);
/** Child process**/
srand(time(NULL)+getpid()); // sets the randomness of the number associted with process id
randomNum = rand()% 201 + (-100); // sets the range of random number from -100 to 100 and stores the random number in randomNum
printf("%d\n" , randomNum); // Prints out the random number
write(pipes[i][1], &randomNum, sizeof randomNum);
close(pipes[i][1]);
exit(0);// Terminates successfully
}
else{
if(wait(NULL)){ // Waits for the child process to end and directs to parent process
int v;
if(read(pipes[i][0], &v, sizeof v)==sizeof(v)){
randomNumSum+=v;
close(pipes[i][0]);
}
}
}
close(pipes[i][1]);
}
printf("%d\n", randomNumSum); // Prints the sum of the random number
return 0;
}
The program goes in infinite loop after second process.
edit
The OP has made significant changes to the question, it's not the same question as it was yesterday. This answer might henceforth make no sense any more.
end edit
The reason for this is that fork() creates a new independent process with its
own virtual memory. It only inherits the values from the parent, the forked process do not share variables
with the parents. So randomNumSum is for every child a unique variable and
changing it does not affect the randomNumSum of the parent.
You need to use for example pipes for communication between parents and
children, the children write the results in the pipe, the parent reads from the
children.
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
if(argc != 2)
{
fprintf(stderr, "usage: %s num_of_children\n", argv[0]);
return 0;
}
int noc = atoi(argv[1]);
if(noc <= 0)
{
fprintf(stderr, "Invalid number of children\n");
return 1;
}
int pipes[noc][2];
pid_t pids[noc];
for(size_t i = 0; i < noc; ++i)
{
if(pipe(pipes[i]) == -1)
{
perror("pipe");
pids[i] = -2; // used later for error checking
continue;
}
pids[i] = fork();
if(pids[i] == -1)
{
perror("fork");
continue;
}
if(pids[i] == 0)
{
// CHILD
// closing reading end
close(pipes[i][0]);
srand(time(NULL)+getpid());
int r = rand()% 201 + (-100);
printf("Child %zu: r = %d\n", i, r);
// sending value to parent
write(pipes[i][1], &r, sizeof r);
close(pipes[i][1]);
return 0;
}
// closing writing end
close(pipes[i][1]);
}
int sum = 0;
for(size_t i = 0; i < noc; ++i)
{
if(pids[i] == -2)
{
fprintf(stderr, "Pipe could not be created for child %zu\n", i);
continue;
}
if(pids[i] == -1)
{
fprintf(stderr, "Child %zu was not started\n", i);
close(pipes[i][0]);
continue;
}
int status;
if(waitpid(pids[i], &status, 0) == -1)
{
fprintf(stderr, "Could not wait for child %zu\n", i);
close(pipes[i][0]);
continue;
}
if(WIFEXITED(status) && WEXITSTATUS(status) == 0)
{
int v;
if(read(pipes[i][0], &v, sizeof v) != sizeof(v))
{
fprintf(stderr, "Could not read from child %zu\n", i);
close(pipes[i][0]);
continue;
}
sum += v;
close(pipes[i][0]);
} else
printf("Child %zu did not exit normally\n", i);
}
printf("The sum is: %d\n", sum);
return 0;
}
Gives me the output:
Child 0: r = -6
Child 1: r = 63
Child 3: r = 78
Child 2: r = 77
Child 4: r = -47
The sum is: 165
So the technique here is the creation of the pipes with the pipe. A pipe
is a unidirectional data channel that can be used for interprocess communicationcite.
With a pipe two processes can communicate with each other, but the pipe has only
one direction. In this example the child process will write into the pipe and
the parent will read from the pipe.
That's why before doing the fork, the parent creates the pipe, does the fork
and then closes the it's writing end of the pipe. The child closes it's reading
end of the pipe. Then the child calculates the value and writes into the pipe
the value it calculated and exists with the status 0.
After creating the children the parent waits for the children to terminate. If
the children terminate normally and with exit status 0, the parent reads from
the pipe and gets the calculated value of the child.
Btw, as David C. Rankin points out in the comments, your method of getting
a random value in the range [-100, 100] is incorrect. rand()% 201 + (-100)
would give you values between -100 and 100, because rand()%201 gives you a
value between 0 and 200.
edit2
OP asked in the comments
based on my understanding can I just return randonNum instead of exit(0) and do the computation where I calling wait(NULL) and call wait(randomNum)?
Yes, you can use the exit status of a process to send information back to the
parent without the need of creating a pipe. But I think this is not a particular
good solution for these reasons:
the exit status in Unix/POSIX is a unsigned 8-bit value, meaning the exit
codes are in the range [0, 255]. So if your random value is let's say -1, the
parent process will see 255. In your case that wouldn't be such a problem,
because you for values greater than 127, you can subtract 256 to get the
negative value.
You can only return an (unsigned) 8-bit value. If your child process has to
send something more "complex" like a 16-bit value, a float, double, or a
struct, you cannot use the exit status, so you
are limiting what you can return to the parent. When you want to return
something more "complex" than a 8-bit value, then a pipe is perfect tool for that.
I consider it as a hack to use the exit status to send other information
that is not an error value. The purpose of the exit status is that a process
can tell it's parent that it exited without an error by returning 0, or that it
exited with an error and the exit status has the error code. That's why I
consider it a hack, for me it's like using a screwdriver instead of a hammer for
nailing nails.
Your wait call would be invalid though, because wait expects a pointer to
int and you would need to use the macros WIFEXITED and WEXITSTATUS to get
the exit status. But the problem of using wait in this case is that wait
returns -1 on error and you wouldn't be able to tell for which child it returned
-1 and how many waits you have to
call to wait for the rest of the children. The children don't end in the same order as you
forked them, so you would need to keep track which child has been wait()ed.
It's much more simpler to use waitpid. With waitpid you can wait for a
particular child. I personally prefer waitpid here.
So, changing the code to do the same without pipes and using the exit status:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
if(argc != 2)
{
fprintf(stderr, "usage: %s num_of_children\n", argv[0]);
return 0;
}
int noc = atoi(argv[1]);
if(noc <= 0)
{
fprintf(stderr, "Invalid number of children\n");
return 1;
}
pid_t pids[noc];
for(size_t i = 0; i < noc; ++i)
{
pids[i] = fork();
if(pids[i] == -1)
{
perror("fork");
continue;
}
if(pids[i] == 0)
{
// CHILD
srand(time(NULL)+getpid());
int r = rand()% 201 + (-100);
printf("Child %zu: r = %d\n", i, r);
exit(r);
}
}
int sum = 0;
for(size_t i = 0; i < noc; ++i)
{
if(pids[i] == -1)
{
fprintf(stderr, "Child %zu was not started\n", i);
continue;
}
int status;
if(waitpid(pids[i], &status, 0) == -1)
{
fprintf(stderr, "Could not wait for child %zu\n", i);
continue;
}
if(WIFEXITED(status))
{
int v = WEXITSTATUS(status);
// checking if the child wrote a 8-bit negative value
// in 2-complement format
if(v > 127)
v -= 256;
printf("Parent: child %zu returned %d\n", i, v);
sum += v;
} else
fprintf(stderr, "Child %zu did exit abnormally, ignoring\n", i);
}
printf("The sum is: %d\n", sum);
return 0;
}
Gives me the output for 10 children:
Child 0: r = -59
Child 1: r = 73
Child 2: r = 61
Child 3: r = 98
Child 4: r = 18
Child 6: r = 31
Child 5: r = -88
Parent: child 0 returned -59
Parent: child 1 returned 73
Parent: child 2 returned 61
Child 8: r = 58
Parent: child 3 returned 98
Parent: child 4 returned 18
Parent: child 5 returned -88
Child 7: r = 53
Parent: child 6 returned 31
Child 9: r = -43
Parent: child 7 returned 53
Parent: child 8 returned 58
Parent: child 9 returned -43
The sum is: 202
I can not figure out why only 1 child sends data to parent (only the 1st child)..
When I do sleep(5) after the child1 sends data through pipe to parent then the 2nd child sends the same prime number to the parent.
Can someone help me?
//--------------------------Consts---------------------------------
#define NUM_OF_CHILDS 2
#define N 20
#define WIN 5
struct msg{
pid_t _pid;
int _prime;
};
//--------------------------Prototypes-----------------------------
bool is_prime(int num);
void terminate(pid_t child_pid[],int fd[2]);
void do_child(int fd[2]);
void print_pair(const int f_arr[],const int s_arr[]);
//--------------------------Main-------------------------------------
int main()
{
int f_arr[N] = {0},
s_arr[N] = {0},
ind, //running on children fork
count1 = 0,
count2 = 0,
victory1 = 0,
victory2 = 0,
min = 0;
int fd[2];
bool read1 = false,
read2 = false;
srand((unsigned)time(NULL));
pid_t child_pid [NUM_OF_CHILDS];//children pid status array
struct msg msg1;
if (pipe(fd) == -1)//pipe fd
{
perror("cannot open pipe");
exit(EXIT_FAILURE);
}
for(ind = 0; ind < NUM_OF_CHILDS; ind++)
{
child_pid[ind] = fork();// duplicate the current process
if (child_pid[ind] < 0)//fork failed
{
perror("Cannot fork()");
exit(EXIT_FAILURE);
}
if(child_pid[ind] == 0)/* child : sends message to parent*/
do_child(fd);
}
/* parent : receives message from child */
close(fd[1]); // close the write-end of the pipe
//read data from pipe
while(read(fd[0],&msg1,sizeof(struct msg)) > 0)
{
if(child_pid[0] == msg1._pid)
{
f_arr[count1++] = msg1._prime;
read1 = true;
}
else
{
s_arr[count2++] = msg1._prime;
read2 = true;
}
if(read1 && read2)
{
if(f_arr[min] > s_arr[min])
victory1++;
else if(f_arr[min] < s_arr[min])
victory2++;
read1 = false;
read2 = false;
min++;
}
if(victory1 == WIN || victory2 == WIN)
terminate(child_pid,fd);
}
close(fd[0]);// close the read-end of the pipe
print_pair(f_arr,s_arr);
return EXIT_SUCCESS ;
}
//---------------------------------------------------------------------
//checking if number is a prime number or not
//and return true or false
bool is_prime(int num)
{
int i;
if(num==0 || num==1 || num==2)
return false;
for(i=2;i<=num/2;i++)
{
//the number is not prime
if(num%i == 0)
return false;
}
//the number is prime
return true;
}
//----------------------------------------------------------------
void do_child(int fd[2])
{
struct msg message;
int num;
close(fd[0]);
while (1)
{
num = rand() % 1000;
if(is_prime(num))
{
message._prime = num;
message._pid = getpid();
write(fd[1], &message, sizeof(struct msg));
}
}
}
//----------------------------------------------------------------
void terminate(pid_t child_pid[],int fd[2])
{
int ind,
loop;
for(ind = 0; ind < NUM_OF_CHILDS; ind++)
{
close(fd[1]);
//first to give the process an opportunity to die gratefully before
//using SIGKILL
kill(child_pid[ind], SIGTERM);
bool died = false;
//It will give the process 5 seconds to die gracefully
for (loop = 0; loop < 5 && !died; ++loop)
{
int pid;
//the time the child process takes to close down gracefully.
sleep(1);
//to get the return status of that process and prevent zombie processes.
if (waitpid(child_pid[ind], &pid, WNOHANG) == child_pid[ind])
died = true;
}
//if SIGTERM did not killed the child do SIGKILL
if (!died)
{
int pid;
kill(child_pid[ind], SIGKILL);
waitpid(child_pid[ind], &pid, 0);// harvest the zombie
}
}
}
//------------------------------------------------------------------
void print_pair(const int f_arr[],const int s_arr[])
{
int ind;
for(ind = 0; ind < N; ind++)
{
if(f_arr[ind] == 0 && s_arr[ind] == 0)
break;
printf("(%d,%d)\n",f_arr[ind],s_arr[ind]);
}
}
First, the two child processes are generating the same pseudorandom sequence because they're starting with the same seed. To have any chance of different numbers, you need to seed them after the fork, and probably use something that changes more than once per second (the chance of the two of them having different values of time() is very small even if you moved the srand(time(NULL)) after the fork).
Second, you are receiving all the numbers from the first process because it has a head start. There's plenty of time to write to the pipe while the second process is being created. The parent doesn't start reading until after both children are created, so the first child fills the pipe buffer and then blocks. Pipe buffers are at least a few kilobytes.
Even when I slowed down the child process by making it print the numbers to stderr, the first one still generated hundreds of numbers before the second one got going.
So what happens in your main loop when there are hundreds of messages arriving from child 1 and none from child 2? Your f_arr array overflows because it only has room for 20. After that, anything can happen.
The simplest way to prevent that would be to check whether count1 == N before attempting to store a number into f_arr[count1++], and if so, just continue; to the next message. You should do the same for messages from the second child, even though it's not likely to happen.
This way you'll be accepting at most N messages from each child, and ignoring the rest. You'll need to add another end condition to the main loop: if both children have sent N messages, you need to stop.
Another way to go would be to use a separate pipe for each child and alternate reading from both pipes to keep them synchronized, but I have a feeling you were deliberately avoiding that.
I am writing on a pipe 10 integers, so i call write 10 times and then i want to call read pipe only once and store the written integers into an array of size 10 and after that add all the integers from the array into a total sum. The problem is that i get only 9 integers after reading. What i am doing wrong?
int main()
{
int fd[2];
int total = 0;
int result;
int nbytes;
int child;
int subVector;
int written;
static int readSum[P];
int partialSum;
if(pipe(fd) < 0){
perror("pipe");
}
for(child = 0; child < P; child++){
if((pid[child] = fork()) < 0){
perror("fork");
exit(1);
}
else if(pid[child] == 0){
close(fd[0]);
partialSum = getSubvectorSum(elementsList,child,P,SIZE);
//printf("Partial sum: %d by child #%d\n",partialSum,getpid());
written = write(fd[1],&partialSum,sizeof partialSum);
//printf("Child #%d has written: %d bytes.\n",getpid(),written);
if(written == 0){
printf("Writting not performed.");
}
close(fd[1]);
exit(0);
}
}
close(fd[1]);
int status = 0;
nbytes = read(fd[0],&readSum,sizeof readSum);
printf("Parent reads %d bytes\n",nbytes);
if(nbytes > 0){
for(child =0;child<P;child++){
total += readSum[child];
printf("Partial sum in father: %d\n",readSum[child]);
}
}
else{
printf("Failed to read.");
}
}
You are ignoring the wisdom of the sage Rolling Stones and not accepting that you can't always get what you want but sometimes you get what you need.
(1) There is no guarantee all your children have run and written to the pipe before the parent tries to read.
(2) There is no guarantee even if (1) did take place that your read would return all 10 integers in one read. read can (and often will) return less than you ask for.
One way to cover this is to have your parent wait on its children so you know they completed and then to read in a loop until you read everything you need.
http://linux.die.net/man/2/read
Read returns available data, not the requested amount, use cycle and check return value on each iteration.
I'm a little confused on how to properly use pipe() to pass integer values between two processes.
In my program I first create a pipe, then I fork it. I assume I have "Two" pipes then?
From what I understand, this is my assignment.
My parent goes through a for loop checking an integer value "i" for a certain operation, increases a count variable, and saves value into an array. After each check my parent should pass an integer value, "i" to my child through a pipe. My child then uses that integer value, does some check on the value, and should increase a count variable, and save the result in a [shared?] array. Eventually; the child should return it's final count to the parent, who then prints out the two counts, and the "Shared" array.
-> I'm not sure I need to have a shared array or to save the results at all. I may only need the counts - the homework was ambiguous and I'm awaiting a response from the professor. Also; can I even do a shared array between processes? It sounds like a start of some problem to me.
-> Here are my questions:
One; how do I use pipes for integers? I've only seen them for character arrays and previous answers don't seem to think this is possible or legal..? I'm not sure. There was no resolution that I could find on it.
-> How do I use a unidirectional pipe to pass integers to a child? And have the child return something? I'm not sure how I'm able to... differentiate between the two pipes. I do "know" [or think I know] that I have to close one unused portion of each pipe to avoid "Some vague problem".
Sorry for the dumb questions; I haven't been taught processes (aside from fork) or pipes (at all) yet in this class - so I'm not really sure where to start!
Heres parts of my code - it's not pretty and it doesn't work and I don't expect it to. It's more of a shell placeholder. Once I figure out how to use a pipe - I'd Probably make the code make sense.
int main(void)
{
int fd[2];
pid_t childpid;
pid_t parentpid;
int i;
int threecount = 0;
int fivecount = 0;;
int results [MAXSIZE];
parentpid = getpid(); //Get current process ID number
pipe(fd);
childpid = fork();
if(childpid == 0){
close(fd[0]); //Closing this for some other reason
}
int j = 0;
if(childpid > 0)
close(fd[1]); //Closing this for some reason
if( childpid == -1 )
{
perror("Failed to fork\n");
return 1;
}
if (childpid > 0)
{
for(i = 1; i < MAXSIZE;i++)
{
if(i % 5 == 0)
{
fivecount++;
i = results[j];
j++;
wait(NULL);
}
}
}
else if (childpid == 0)
{
if(i % 3 == 0) //This i here should probably be the i value above, piped to the child
{
threecount++;
i = results[j]; //This should be part of th pipe
j++; //Trying to keep count of that shared array, not really the right way to do it though.
}
}
printf("%d %d \n", fivecount,threecount);
return 0;
}
This is about as lame (and no error checking, btw) a sample as I can muster for using a pipe to send int from a parent to a child process, where the child was launched from fork(). It gets more complicated (obviously) for sending and receiving data, but i can't do everything for you. This just forks and waits for an int (actually, the number of bytes that are used by an int) from the child.
Update: Added send+response two-way communication example after this one. See the second code listing for more information.
Hope it helps.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd[2];
int val = 0;
// create pipe descriptors
pipe(fd);
// fork() returns 0 for child process, child-pid for parent process.
if (fork() != 0)
{
// parent: writing only, so close read-descriptor.
close(fd[0]);
// send the value on the write-descriptor.
val = 100;
write(fd[1], &val, sizeof(val));
printf("Parent(%d) send value: %d\n", getpid(), val);
// close the write descriptor
close(fd[1]);
}
else
{ // child: reading only, so close the write-descriptor
close(fd[1]);
// now read the data (will block)
read(fd[0], &val, sizeof(val));
printf("Child(%d) received value: %d\n", getpid(), val);
// close the read-descriptor
close(fd[0]);
}
return 0;
}
Output:
Parent(5943) send value: 100
Child(5945) received value: 100
Update: Expanded to include send+response using two pipe sets
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
// some macros to make the code more understandable
// regarding which pipe to use to a read/write operation
//
// Parent: reads from P1_READ, writes on P1_WRITE
// Child: reads from P2_READ, writes on P2_WRITE
#define P1_READ 0
#define P2_WRITE 1
#define P2_READ 2
#define P1_WRITE 3
// the total number of pipe *pairs* we need
#define NUM_PIPES 2
int main(int argc, char *argv[])
{
int fd[2*NUM_PIPES];
int val = 0, len, i;
pid_t pid;
// create all the descriptor pairs we need
for (i=0; i<NUM_PIPES; ++i)
{
if (pipe(fd+(i*2)) < 0)
{
perror("Failed to allocate pipes");
exit(EXIT_FAILURE);
}
}
// fork() returns 0 for child process, child-pid for parent process.
if ((pid = fork()) < 0)
{
perror("Failed to fork process");
return EXIT_FAILURE;
}
// if the pid is zero, this is the child process
if (pid == 0)
{
// Child. Start by closing descriptors we
// don't need in this process
close(fd[P1_READ]);
close(fd[P1_WRITE]);
// used for output
pid = getpid();
// wait for parent to send us a value
len = read(fd[P2_READ], &val, sizeof(val));
if (len < 0)
{
perror("Child: Failed to read data from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
// not an error, but certainly unexpected
fprintf(stderr, "Child: Read EOF from pipe");
}
else
{
// report what we received
printf("Child(%d): Received %d\n", pid, val);
// now double it and send it back
val *= 2;
printf("Child(%d): Sending %d back\n", pid, val);
if (write(fd[P2_WRITE], &val, sizeof(val)) < 0)
{
perror("Child: Failed to write response value");
exit(EXIT_FAILURE);
}
}
// finished. close remaining descriptors.
close(fd[P2_READ]);
close(fd[P2_WRITE]);
return EXIT_SUCCESS;
}
// Parent. close unneeded descriptors
close(fd[P2_READ]);
close(fd[P2_WRITE]);
// used for output
pid = getpid();
// send a value to the child
val = 42;
printf("Parent(%d): Sending %d to child\n", pid, val);
if (write(fd[P1_WRITE], &val, sizeof(val)) != sizeof(val))
{
perror("Parent: Failed to send value to child ");
exit(EXIT_FAILURE);
}
// now wait for a response
len = read(fd[P1_READ], &val, sizeof(val));
if (len < 0)
{
perror("Parent: failed to read value from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
// not an error, but certainly unexpected
fprintf(stderr, "Parent(%d): Read EOF from pipe", pid);
}
else
{
// report what we received
printf("Parent(%d): Received %d\n", pid, val);
}
// close down remaining descriptors
close(fd[P1_READ]);
close(fd[P1_WRITE]);
// wait for child termination
wait(NULL);
return EXIT_SUCCESS;
}
(compile with, e.g., gcc thisfile.c -o test)
Output
Parent(2794): Sending 42 to child
Child(2797): Received 42
Child(2797): Sending 84 back
Parent(2794): Received 84