리눅스에서 fork 에러
글쓴이: klued / 작성시간: 금, 2020/05/01 - 5:03오전
리눅스환경에서 연습하고잇는데 출력이 자꾸 이상해서 질문합니다.
메인함수와 자식프로세스에서 실행할 child라는 실행파일 두가지로 구성되있습니다.
메인함수
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(void){ pid_t pid1; pid_t pid2; pid1= fork(); pid2=fork(); int status1,status2,sum1,sum2,avrg; FILE *rfp1; FILE *rfp2; char *argv[5]; argv[0]="child"; argv[1]="data.txt"; argv[2]="1"; argv[3]="50"; argv[4]=NULL; char *argv2[5]; argv2[0]="child"; argv2[1]="data.txt"; argv2[2]="51"; argv2[3]="100"; argv2[4]=NULL; if(pid1==0); //첫번째 child프로세스 { printf("child process- my pid : %d , parents pid : %d \n",(int)getpid(),(int)getppid()); if(execv("./child",argv)==-1){ perror("execv error"); exit(1); //에러 } printf("child process1"); exit(0); } if(pid2==0); //두번째 child 프로세스 { printf("-->child process\n"); if(execv("./child",argv2)==-1){ perror("execv error"); exit(1); //에러 } printf("-->child process2"); exit(0); } printf("-->parent process1"); while (waitpid(pid1,&status1,WNOHANG)==0){ printf("parent still wait pid 1"); sleep(1); } while (waitpid(pid2,&status2,WNOHANG)==0){ printf("parent still wait pid 2"); sleep(1); } printf("child exit status : %d %d \n",status1>>8,status2>>8); rfp1=fopen("result1.txt","r"); fscanf(rfp1,"%d",&sum1); rfp2=fopen("result2.txt","r"); fscanf(rfp2,"%d",&sum2); avrg= (sum1+sum2)/100; printf("평균은 %d이다.",avrg); return 0; }
------------------------------------------------------------
child.c
#include <stdio.h> #include <stdlib.h> // child data.txt 1 50 NULL int main(int argc, char** argv) { FILE *rfp; FILE *wfp1; FILE *wfp2; int i,id,score,n,s,f,sum=0; printf("child 실행 파일 실행 성공.."); // data.txt 받고, 파일 열기. if( (rfp = fopen(argv[1],"r")) == NULL) { perror("fopen: data.txt"); exit(1); } for(i=argv[2];i++;i<=argv[3]) { fscanf(rfp,"%d %d",&id,&score); sum+=score; } fclose(argv[1]); if(argv[2]==1){ wfp1=fopen("result1.txt","w"); fputs(sum,wfp1); fclose("result1.txt"); } else if(argv[2]==51){ wfp2=fopen("result2.txt","w"); fputs(sum,wfp2); fclose("result2.txt"); } return 0; }
data.txt라는 파일에서 아이디와성적을받고 성적 합산 평균 내려고하는데,
리눅스환경에서 명령어를 실행하면
child process- my pid : 1261 , parents pid : 22331
child process- my pid : 1263 , parents pid : 1261
child process- my pid : 1262 , parents pid : 1261
이러고 실행은 멈춥니다.
혹은 child의 fopen 부분에서 bad address 경고가 또 한 3번 출력되구요..
해결책을 모르겠어서 질문합니다.
Forums:
질답 포럼에 답변 받은 후 질문을 삭제할 경우 해당
질답 포럼에 답변 받은 후 질문을 삭제할 경우 해당 계정 제한 합니다! 답변 있는 질문 삭제 하지 마십시오!
코드 입력 또는 들여쓰기가 필요한 내용의 경우,
<code> tag block 을 이용하여 작성 하십시오.
For code entry or indentation, use the <code> tag block.
<code lang="c">
</code>
댓글 달기