C program asking for user input multiple times - c

Writing a very basic C program that demonstrates shared memory. The program needs to keep calculating the sum of two inputs until the user does a ^C (not shown here).
What I have so far is that my parent captures user input, then tells the child to calculate the sum, which the parent then prints the sum (as the assignment suggests).
Attached is my code.
// Fork the process
while(1) {
// Declare a shared memory integer array
int *shared_ints = mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
int x;
int y;
shared_ints[3] = 0;
if((pid = fork()) < 0) {
printf("Fork error \n");
exit(-1);
} else if(pid > 0 && shared_ints[3] == 0) { // Parent code
// Ask user for first input
printf("Enter your first number:");
scanf("%d", &x);
printf("\n");
// Ask user for second input
printf("Enter your second number:");
scanf("%d", &y);
printf("\n");
// Assign first value to shared memory
shared_ints[0] = x;
// Assign second value to shared memory
shared_ints[1] = y;
// Tell child that it can compute the sum now
shared_ints[3] = 1;
// Trap parent in a while-loop while the child
// computes the sum
while(shared_ints[3] == 1);
// Child has completed calculating the sum and
// the parent can print the sum
if(shared_ints[3] == 2) {
printf("The sum is: %d", shared_ints[2]);
printf("\n");
}
} else { // Child code
// Wait for parent to accept input values
while(shared_ints[3] == 0);
// Calculate the sum
shared_ints[2] = shared_ints[0] + shared_ints[1];
// Tell parent sum has been calculated
shared_ints[3] = 2;
}
}
The sum calculation works until I go to the fourth-iteration of the sum calculation (this is the output):
Created shared memory object /my_shared_memory
Shared memory segment allocated correctly (16 bytes).
Enter your first number:1
Enter your second number:2
The sum is: 3
Enter your first number:Enter your first number:3
Enter your second number:4
The sum is: 7
Enter your first number:Enter your first number:5
Enter your second number:6
The sum is: 11
Enter your first number:Enter your first number:7
Enter your second number:8
Enter your second number:9
Enter your second number:
An interesting bug I see is that after I print the sum, the program asks for the first input twice as suggested here: Enter your first number:Enter your first number:3, and then in the fourth sum iteration, it asks for the second number several times before calculating the sum.

The trouble is that you're forking on each iteration of the outer while loop, so the first time around, you have one child, then you have a child that thinks it has grown up and is a parent (as well as the parent that knows it is a parent). And it gets worse as you continue.
Another problem is that you're allocating shared memory on each iteration of the outer while loop. I'm not sure it's exactly a memory leak, but it probably isn't a good idea.
To fix:
Move the mmap() and the fork() outside the while (1) loop.
The parent process will have a loop — in its own function, not all inside main(), please — that reads from the user, transfers to the child, reads the result from the child, and continues.
The child process will have a loop — also in its own function, please — that reads from the parent, calculates, and continues.
Make sure the child knows how to exit when the parent exits.
Ideally, use a synchronization mechanism other than busy waiting. A couple of mutexes or a couple of semaphores would be good. The processes would wait to be told there's work for them to do, rather than spinning their wheels (very fast) while waiting for the next task.
More or less working code
This uses a header "stderr.h" and functions err_setarg0() and err_syserr() from code I wrote because error reporting is crucial and these make it easy. You should be able to find code on SO from me with working versions of that header and those functions.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "stderr.h"
static void be_childish(int *shared_ints);
static void be_parental(int *shared_ints);
int main(int argc, char **argv)
{
const char *file = "fidget";
int shared_seg_size = 4 * sizeof(int);
err_setarg0(argv[0]);
if (argc > 1)
file = argv[1];
int fd = open(file, O_RDWR|O_CREAT, 0600);
if (fd < 0)
err_syserr("Failed to open file %s for read/write\n", file);
/* Assume sizeof(int) == 4 */
if (write(fd, "abcdefghijklmnop", shared_seg_size) != shared_seg_size)
err_syserr("Failed to write %d bytes to %s\n", shared_seg_size, file);
int *shared_ints = mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shared_ints == 0)
err_syserr("Failed to mmap file %s\n", file);
shared_ints[3] = 0;
int pid;
if ((pid = fork()) == -1)
err_syserr("Failed to fork\n");
else if (pid == 0)
be_childish(shared_ints);
else
be_parental(shared_ints);
return 0;
}
static void be_childish(int *shared_ints)
{
while (1)
{
// Wait for parent to generate input values
while (shared_ints[3] == 0 || shared_ints[3] == 2)
{
printf("Child: %d\n", shared_ints[3]);
usleep(500000);
}
if (shared_ints[3] != 1)
{
printf("Child: exiting\n");
return;
}
// Calculate the sum
shared_ints[2] = shared_ints[0] + shared_ints[1];
printf("Child: calculated %d + %d = %d\n", shared_ints[0], shared_ints[1], shared_ints[2]);
// Tell parent sum has been calculated
shared_ints[3] = 2;
}
}
static void be_parental(int *shared_ints)
{
while (1)
{
int x;
int y;
// Ask user for first input
printf("Enter your first number:");
if (scanf("%d", &x) != 1)
{
printf("Parent: exiting\n");
shared_ints[3] = -1; /* Tell child to exit */
return;
}
printf("\n");
// Ask user for second input
printf("Enter your second number:");
if (scanf("%d", &y) != 1)
{
printf("Parent: exiting\n");
shared_ints[3] = -1; /* Tell child to exit */
return;
}
printf("\n");
// Assign first value to shared memory
shared_ints[0] = x;
// Assign second value to shared memory
shared_ints[1] = y;
// Tell child that it can compute the sum now
shared_ints[3] = 1;
// Trap parent in a while-loop while the child
// computes the sum
while (shared_ints[3] == 1)
{
printf("Parent: %d\n", shared_ints[3]);
usleep(500000);
}
// Child has completed calculating the sum and
// the parent can print the sum
if (shared_ints[3] == 2)
{
printf("The sum is: %d", shared_ints[2]);
printf("\n");
}
else
{
printf("Parent: unexpected control %d - exiting\n", shared_ints[2]);
shared_ints[3] = -1; /* Tell child to exit */
return;
}
}
}
This code has debugging in the busy-wait loops, and a delay of 0.5 seconds on each read cycle. You can tweak that to suit yourself, and lose the output once your sure it's working for you, too. Note that the code destroys a file fidget unless you specify an alternative name to be created/destroyed. It does not remove the file as it exits; it probably should.
Sample run
$ ./dualproc
Enter your first number:Child: 0
1
Enter your second number:Child: 0
2
Parent: 1
Child: calculated 1 + 2 = 3
Child: 2
The sum is: 3
Enter your first number:Child: 2
Child: 2
3
Enter your second number:Child: 2
4
Parent: 1
Child: calculated 3 + 4 = 7
Child: 2
The sum is: 7
Enter your first number:Child: 2
q
Parent: exiting
$ Child: exiting
$
The parent exited before the child did; no big surprise there. You could upgrade the code to use wait() to wait for the child to exit if you preferred.

NOTE: There is a problem here in a corner case where the parent quits and the child is still waiting for the parents input value - can happen if the user breaks the program when shared_ints[3] != 0
To demonstrate #Jonathan Leffler's excellent answer, here's my suggestion for a fix:
/* These are better declared outside the while loop */
// Declare a shared memory integer array
int *shared_ints = mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
int x;
int y;
// Fork the process
while(1) {
shared_ints[3] = 0;
if((pid = fork()) < 0) {
printf("Fork error \n");
exit(-1);
} else if(pid > 0 && shared_ints[3] == 0) { // Parent code
// Ask user for first input
printf("Enter your first number:");
scanf("%d", &x);
printf("\n");
// Ask user for second input
printf("Enter your second number:");
scanf("%d", &y);
printf("\n");
// Assign first value to shared memory
shared_ints[0] = x;
// Assign second value to shared memory
shared_ints[1] = y;
// Tell child that it can compute the sum now
shared_ints[3] = 1;
// Trap parent in a while-loop while the child
// computes the sum
while(shared_ints[3] == 1);
// Child has completed calculating the sum and
// the parent can print the sum
if(shared_ints[3] == 2) {
printf("The sum is: %d", shared_ints[2]);
printf("\n");
}
} else { // Child code
// Wait for parent to accept input values
while(shared_ints[3] == 0);
// Calculate the sum
shared_ints[2] = shared_ints[0] + shared_ints[1];
// Tell parent sum has been calculated
shared_ints[3] = 2;
/* Child process should finish, so it doesn't fork
and in the upper while loop. this is a fast way to do it */
exit(0);
}
}

At each iteration of the big while loop, the parent and child process are calling fork() in this line:
if((pid = fork()) < 0) {
You are repeatedly spawning more child processes after every iteration and can be creating unexpected interactions.

Related

Pipe's related arguments to pass to a function?

I'm a beginner in C programming and I started learning about pipes today.
I need them because my program has to run up to 4 processes at the time, so to avoid creating more processes than those required, I have to use a shared variable between all of them to keep track how may can still be created.
I tried to simplify my program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void forking(int p, int pid);
int main(int argc, char *argv[])
{
int fd[2];
int p = 4; // Max number of processes that can run at the same time
int pid;
if(pipe(fd) == -1)
{
perror("pipe: ");
return 0;
}
//It will try the function forking 10 times to execute SOME CODE that
// changes everytime something operates on it
for(int i = 0; i < 10; i++)
{
forking(p, pid);
}
return 0;
}
void forking(int p, int pid)
{
if (p > 0) //We can create another process
{
p -= 1; // update the p before creating a child process
write(fd[1], &p, (sizeof(int)*3)); //Tell everyone about the update
pid = fork();
if (pid == 0)
{
//The child process turn to elaborate SOME CODE
// SOME CODE
// Then there will be a point where
// we will need to check if the p has been modified!
read(fd[0], &p, sizeof(int)*3);
//So that forking can decide whether we can create another process
// to operate on SOME OTHER CODE
forking(p, pid);
//Once we are done, we can terminate the child
//but first we'll need to update the process n° p
p += 1;
write(fd[1], &p, (sizeof(int)*3));
exit(0);
}
else if(pid > 1) //Father time
{
// check the updated value
//the father will do nothing
// since a process it's already on it (on the SOME CODE part)
return;
}
}
else
{
//else the father does SOME CODE itself
// SOME CODE
}
return;
}
My 2 doubts is whether I should pass something else to the function "forking" (which can be recursive), like "fd", or if it is okay to just leave the code like this, and whether this will have the desired result.
Hopefully I made myself clear enough.
EDIT 1:
void forking(int p, int pid, int *fd)
{
if (p > 0) //We can create another process
{
p -= 1; // update the p before creating a child process
write(fd[1], &p, (sizeof(int)*3)); //Tell everyone about the update
pid = fork();
if (pid == 0)
{
//The child process turn to elaborate SOME CODE
// SOME CODE
// Then there will be a point where
// we will need to check if the p has been modified!
read(fd[0], &p, sizeof(int)*3);
//So that forking can decide whether we can create another process
// to operate on SOME OTHER CODE
forking(p, pid, fd);
//Once we are done, we can terminate the child
//but first we'll need to update the process n° p
p += 1;
write(fd[1], &p, (sizeof(int)*3));
exit(0);
}
else if(pid > 1) //Father time
{
// check the updated value
//the father will do nothing
// since a process it's already on it (on the SOME CODE part)
return;
}
}
else
{
//else the father does SOME CODE itself
// SOME CODE
}
return;
}
Passing fd resulted as a success, now I'm wondering whether I should add pipe(fd) at the start of the forking program like so . . .
void forking(int p, int pid, int *fd)
{
if(pipe(fd) == -1)
{
perror("pipe: ");
return;
}
//Rest of the code
}

Processes in C for Linux(Ubuntu)

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

C - create two processes which can generate odd and even integers

I have this assignment where I have to create two processes and each process has to generate 50 integers which are odd or even.
Write a simple sequence-number system through which two processes, P1 and P2, can each obtain 50 unique integers, such that one receives all the odd and the other all the even numbers. Use the fork() call to create P1 and P2. Given a file, F, containing a single number, each process must perform the following steps:
a. Open F.
b. Read the sequence number N from the file.
c. Close F.
d. Output N and the process' PID (either on screen or test file).
e. Increment N by 1
f. Open F.
g. Write N to F.
h. Flush F.
i. Close F
As suggested by SO user I have created a loop in each process and ran the steps as mentioned above. But I am not sure if this approach is correct. I have asked my Teaching assistant for help and he suggested to do the same(using sleep call and waiting for a valid integer). But the thing is I can obtain the same results without using the sleep call. So I am not sure if I am applying the logic properly to code. Can someone please help?
This is my implementation:
void getUniqueNumbers() {
struct process p1;
struct process p2;
int numberFromFile;
pid_t pid = fork();
// Process 1
if (pid == 0) {
int p1Counter = 0;
p1.processId = getpid();
while(p1Counter < numLimit) {
numberFromFile = getNumberFromFile();
if (numberFromFile % 2 == 0) { // even
p1.numbers[p1Counter] = numberFromFile;
printf("N: %d, PID: %d\n", numberFromFile, p1.processId);
numberFromFile++;
writeNumberToFile(numberFromFile);
p1Counter++;
}
else {
sleep(1);
}
}
}
// Process 2
else if (pid > 0 ) {
int p2Counter = 0;
p2.processId = getpid();
while(p2Counter < numLimit) {
numberFromFile = getNumberFromFile();
if (numberFromFile % 2 != 0) { // odd
p2.numbers[p2Counter] = numberFromFile;
printf("N: %d, PID: %d\n", numberFromFile, p2.processId);
numberFromFile++;
writeNumberToFile(numberFromFile);
p2Counter++;
}
else {
sleep(1);
}
}
}
else {
printf("Error: Could not create process\n");
}
}
Read/Write functions:
// Returns the number included in user provided file
int getNumberFromFile() {
FILE *fp = fopen(fileName, "rb");
int num = 0;
if (fp != 0) {
char line[10];
if (fgets(line, sizeof(line), fp) != 0)
num = atoi(line);
fclose(fp);
}
return num;
}
// Writes a given number to the user provided file
void writeNumberToFile(int num) {
FILE *fp = fopen(fileName, "w");
if (fp != 0) {
fprintf(fp, "%d", num);
fclose(fp);
}
}
The code looks ok. It can be simplified a lot though.
void getUniqueNumbers()
{
struct process p; // We need only 1 structure
size_t counter = 0; // sample counter
int oddEven; // flag if we are parent
pid_t pid = fork(); // Fork here
if (-1 == pid)
{
abort(); // simply die on error
}
oddEven = 0 == pid ? 0 : 1;
p.processId = getpid(); // We are either child or parent.
while (counter < numLimit)
{
int numberFromFile = getNumberFromFile();
if ((numberFromFile & 1) == oddEven)
{
p.numbers[counter++] = numberFromFile;
printf("N: %d, PID: %ld\n", numberFromFile, (long)p.processId);
numberFromFile++;
writeNumberToFile(numberFromFile);
}
sleep(1); // sleep in both cases
// Extra check for parent: if child has died, we are in infinite
// loop, so check it here
if (0 != pid && counter < numLimit)
{
int status = 0;
if (waitpid(pid, &status, WNOHANG) > 0)
{
printf("Child exited with 0x%08X status\n", status);
break;
}
}
}
// wait till child process terminates
if (0 != pid)
{
int status = 0;
waitpid(pid, &status, 0);
printf("Child exited with 0x%08X status\n", status);
}
}
Also, the file reading/writing either should use file lock operations, or atomic file change. It is important to prevent potential errors like one thread is writing number 40006, and another one manages to read 400. Should not happen in real life though.
File locks are needed to prevent concurrent access to the same contents. It can be exclusive lock, or shared read exclusive write.
Atomic modifications are feature that enables to replace file contents atomically, regardless of how many operations it took to write the data. It is an alternative to keep data consistent.

reading a value from a pipe isn't working

I have a program where two child processes are created belonging to the same father. Now the program starts by hitting control C and then works by pressing control Z each time.
Aim is for child 1 to write two numbers to child 2 and child two divides the numbers and writes the result back to child 1 that displays it. As a result two pipes are needed (fd and sd).
I got the first pipe working fine, so the numbers are sending over...in child 2(for debugging) it displays the correct number so if it had 8 and 2....the right answer of 4 is displayed in child 2. Now I can't seem to get this "4" or whatever the result is back to child 1.
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
void handleSignal(int sig)
{
if (sig == SIGTSTP)
{
return;
}
}
int main()
{
int fd[2];
int sd[2];
int pipe1 = 0;
int pipe2 = 0;
pid_t fork1 = 0;
pid_t fork2 = 0;
int num1, num2, result;
int myJump = 0;
int returnResult = 99;
signal(SIGINT, handleSignal);
printf("Waiting for interrupt\n");
pause();
signal(SIGINT, SIG_IGN);
pipe1 = pipe(fd);
pipe2 = pipe(sd);
//pipe checks been omitted...for simplicity
fork1 = fork();
//fork check been omited..for simplicity
signal(SIGTSTP, handleSignal); //wait till control Z is pressed
if (fork1 == 0)
{
dup2(fd[1], 1);
dup2(sd[0], 0);
close(fd[0]);
close(sd[1]);
while(1)
{
pause();
int randNum1 = rand() % 9 + 1;
fprintf(stderr, "Child 1: %d\n", randNum1);
printf("%d\n", randNum1);
fflush(stdout);
scanf("%d", &returnResult);
fprintf(stderr, "result in A :%d \n", returnResult);
}
}
else if (fork1 > 0)
{
fork2 = fork();
if (fork2 == 0)
{
signal(SIGTSTP, handleSignal);
dup2(fd[0], 0);
dup2(sd[1], 1);
close(fd[1]);
close(sd[0]);
if (myJump == 0)
{
pause();
scanf("%d", &num1);
printf("CHild 2: %d\n", num1);
myJump = 1;
}
if (myJump == 1)
{
while (1)
{
pause();
scanf("%d", &num2);
result = num2 / num1;
fprintf(stderr, "result from B: %d \n", result);
num1 = num2;
printf("%d \n", result);
}
}
}
else
{
wait();
}
}
else
{
printf("errror \n");
}
return 0;
}
If anyone could see whats wrong, if you was to run it...it works by hitting control C first then you have to keep hitting control Z. You can then see that the result from child A doesn't match that of B as shown below
Waiting for interrupt
^C^ZChild 1: 2
result in A :99
^ZChild 1: 8
result in A :99
result from B: 4
^ZChild 1: 1
result in A :99
result from B: 0
The pipes are actually working fine... it's scanf() that's failing. When your second child process starts, it calls:
if (myJump == 0)
{
pause();
scanf("%d", &num1);
printf("CHild 2: %d\n", num1); /* <== problem here */
myJump = 1;
}
...and the printf() there leaves "CHild 2: " as the next data in the sd[] pipe. Because of that, when your first child process calls scanf() to read the result from the second, scanf() fails and leaves returnResult unchanged. Since scanf() failed, the data is left on the stream, and future attempts to scanf() the result fail the same way.
How to fix it depends on what you want. If you want your second child process to just return the number it read as the result for the first pass, then just modify the offending printf() to write just the number without the text:
if (myJump == 0)
{
pause();
scanf("%d", &num1);
printf("%d\n", num1); /* <== Changed: number only, no text */
myJump = 1;
}
I should add that although the change mentioned above will fix the problem, you should generally check the return from scanf() to see whether it succeeds and take appropriate action if it doesn't.

Reading from pipe issue

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.

Resources