问题
I am working on a program that will take an integer and create two processes, a parent and a child. The parent will subtract 5 from the integer, pass it to the child who will divide it by 5, and then they will repeat this process 5 times, each time printing the current value of the integer.
The integer can be passed through a text file and be both written and read off of, or a pipeline can be used which ever is simpler.
I have been looking up the systems calls needed, and have a semi working program. I have been stuck for hours however, and I think my issue is that I can't get them to wait for each other to finish because my output is incorrect.
Here is what I got so far.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
#include <fcntl.h>
int main(void)
{
int x=19530;
int w=1;
int fd[2];
pipe(fd);
int pid = fork();
int k;
for (k=0; k<5; k++) {
if (pid>0) {
//int x = 19530;
if ((close(fd[0]))==-1) {
perror("Close:");
}
read(fd[0], &x, sizeof(int));
x=x-5;
write (fd[1], &x, sizeof(int));
printf("X in parent %d\n", x);
close(fd[1]);
close(fd[0]);
} else if (pid==0) {
if ((close(fd[1]))==-1) {
perror("Close:");
}
read(fd[0], &x, sizeof(int));
x=x/5;
printf("X in child %d\n", x);
write (fd[1], &x, sizeof(int));
close(fd[1]);
close(fd[0]);
}
}
return 0;
}
However my output is an issue, I am getting:
X in parent 19525
X in child 3905
Close:: Bad file descriptor
X in parent 19520
Close:: Bad file descriptor
X in parent 19515
Close:: Bad file descriptor
X in parent 19510
Close:: Bad file descriptor
X in parent 19505
Close:: Bad file descriptor
X in child 781
Close:: Bad file descriptor
X in child 156
Close:: Bad file descriptor
X in child 31
Close:: Bad file descriptor
X in child 6
It seems to start off well, but then the child doesn't pass back properly then the parent runs too many times in a row before the child catches up. I also been trying to fix that bad file descriptor but to no avail.
Any help would be greatly appreciated.
Thanks.
回答1:
#include <stdio.h>
#include <unistd.h>
#include <err.h>
#define ok(x) ({ int i_ = (x); if (i_ == -1) err(1, #x); i_; })
enum { p_, c_ }; // parent, child
enum { r_, w_ }; // read, write
int main(void)
{
int x = 19530;
int fd[2][2];
int pid;
ok(pipe(fd[0]));
ok(pipe(fd[1]));
ok(pid = fork());
close(fd[p_][pid ? r_ : w_]);
close(fd[c_][pid ? w_ : r_]);
for (int i = 0; i < 5; i++) {
if (pid) {
x -= 5;
printf("X in parent %d\n", x);
ok(write(fd[p_][w_], &x, sizeof(x)));
ok(read(fd[c_][r_], &x, sizeof(x)));
}
else {
ok(read(fd[p_][r_], &x, sizeof(x)));
x /= 5;
printf("X in child %d\n", x);
ok(write(fd[c_][w_], &x, sizeof(x)));
}
}
return 0;
}
Pipes are unidirectional, so you need two. I used some enums to try and make things easier to read.
来源:https://stackoverflow.com/questions/35302981/linux-system-calls-problems-using-fork-passing-ints-to-child-and-parent-proces