0
我正在尝试使用进程和fork()
来更好地了解它们的工作方式。现在,我试图编写一个程序,该程序需要shell输入并将从输入k
到q
的整数从父进程写入子进程。这是我的代码到目前为止,我不明白为什么它不能正常工作,但我关闭了所有管道,代码非常小。从父进程连续写入到子进程C
#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;
}
我知道此代码应检查其他系统调用一样close()
read
和write
,我也明白,使用atoi
是一个坏主意。我在我的问题中跳过这些内容,尽可能简洁。
当我运行./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.
它仅获得第一个值我得到的输出,我不明白为什么?如果不是这样的话,我会如何在整个过程之间传递从k
到q
的整数流?谢谢!