나는 어떻게 작동하는지 더 잘 이해하기 위해 프로세스 및 fork()
과 함께 놀려고합니다. 지금 당장 나는 셸 입력을 받아 입력 프로세스 k
에서 q
까지의 정수를 자식 프로세스에 쓰는 프로그램을 작성하려고합니다. 지금까지 제 코드를 보았습니다. 왜 제대로 작동하지 않는지 이해하지 못합니다. 모든 파이프를 닫았고 코드는 꽤 작습니다.부모 프로세스에서 자식 프로세스로 연속적으로 씁니다.
#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;
}
나는 또한 atoi
를 사용하는 것은 나쁜 생각을 이해,이 코드는 다른 시스템이 close()
read
및 write
처럼 호출을 확인해야합니다 알고 있습니다. 가능한 한 간결하게 만들기 위해이 질문을 건너 뛰고 있습니다.
내가 뭔가를 첫 번째 값을 점점 ./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
까지의 정수 스트림을 전달할 수 있습니까? 고맙습니다!