问题
The objective is to use dup, dup2 and pipe to communicate between parent and child processes. Just to get a feel of how to use dup and pipes. The function multby, called in by the child process, takes a number as an argument (3) and multiply it with a user input (in this case 5 as printed in parent) to get a product. (which should be 15)
#include <stdio.h>
#include <unistd.h>
void main(int argv, char *argc) {
int testpipe[2];
pipe(testpipe);
int PID = fork();
if (PID == 0) {
dup2(testpipe[0], 0);
close(testpipe[1]);
execl("./multby", "multby", "3", NULL);
close(testpipe[0]);
close(0);
} else {
dup2(testpipe[1], 1);
close(testpipe[0]);
printf("5");
close(1);
close(testpipe[1]);
wait(NULL);
}
}
Here is the code for multby. I also added some fprintf statement to troubleshoot. In particular, it prints out the 2 numbers to be multiplied (which should be 3 and 5 as mentioned above).
#include <stdio.h>
int main(int argv, char *argc[]) {
fprintf(stderr,"exec successful\n");
if (argv < 2) {
fprintf(stderr, "Usage: %s <factor>\n", argc[0]);
return 1;
}
size_t a, b;
sscanf(argc[1], "%zu", &a);
fprintf(stderr, "a: %zu\n", a);
if (scanf("%zu", &b) != 1) {
fprintf(stderr, "No input %zu\n", a);
return 1;
}
fprintf(stderr, "b: %zu\n", b);
printf("%zu", a*b);
fprintf(stderr, "multby successful\n");
return 0;
}
However, this is my result: exec successful a: 3 No input 3
5 was not registered from the read end of the pipe.
Could someone please advise me on what I am doing wrong?
回答1:
You use printf(“5”);
to relay the data to the child, but standard output is at least line-buffered so nothing is written until a newline is sent (or fflush(stdout)
). Then you close(1);
to close standard output, which does not flush the standard I/O buffers. So nothing is sent to the child. Use fclose(stdout);
to get the 5 sent to the child.
来源:https://stackoverflow.com/questions/60250374/why-is-it-that-my-pipe-does-not-read-in-the-printf-despite-replacing-stdin