Seems your
printf("Wrote %i out of %i\n", k, q);
should be
printf("Wrote %i out of %i\n", w, q);
^^
w here
Same when you print it out in the child process.
質問
I'm trying to play with processes and fork()
to get a better idea about how they work. Right now, I'm trying to write a program that takes shell input and writes the integers from inputs k
to q
from the parent process to a child process. Here's my code so far, I don't understand why it's not working properly though, I closed all the pipes and the code is pretty small.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* pipe, fork */
#include <sys/wait.h> /* wait */
#include <sys/types.h> /* pid_t */
void testProc(int k, int q){
pid_t new_proc;
int fd[2];
pipe(fd);
new_proc = fork();
int w;
if (new_proc > 0) {
close(fd[0]);
for(w=k; w < q; w++) {
write(fd[1], &w,sizeof(int));
printf("Wrote %i out of %i\n", k, q);
}
close(fd[1]);
}
else if (new_proc == 0) {
close(fd[1]);
while(read(fd[0], &w, sizeof(int) ) > 0) {
printf("Child received %i out of %i from Parent.\n", k, q);
}
close(fd[0]);
exit(1);
}
else{
printf("Fork failed\n");
exit(1);
}
}
int main(int argc, char *argv[]) {
int n, m;
if (argc != 3) {
fprintf(stderr, "Need 3 arguments\n");
return -1;
}
m = atoi(argv[2]);
n = atoi(argv[1]);
testProc(n, m);
return 0;
}
I realize this code should check the other system calls like close()
read
and write
, I also understand that using atoi
is a bad idea. I'm skipping over these things in my question to make it as concise as possible.
The output I get when I run ./testProc 4 8
Wrote 4 out of 8
Wrote 4 out of 8
Wrote 4 out of 8
Wrote 4 out of 8
Child received 4 out of 8 from Parent.
Child received 4 out of 8 from Parent.
Child received 4 out of 8 from Parent.
Child received 4 out of 8 from Parent.
It's only getting the first value, I don't understand why? How would I pass a stream of integers from k
to q
between processes if not like this? Thank you!
解決
Seems your
printf("Wrote %i out of %i\n", k, q);
should be
printf("Wrote %i out of %i\n", w, q);
^^
w here
Same when you print it out in the child process.