본문 바로가기

컴퓨터/언어,프로그래밍

fork() 함수에관한건데 좀 도와주세요

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
fibo (int n);
int main()
 {
 int a;
 pid_t pid;
 pid=fork();
 if (pid<0) {
  fprintf(stderr,"Fork Failed");
 exit (-1);
    } 
 else if (pid==0){
  execlp("/bin/ls","ls",NULL);

 fibo(a);

     }

else {
 wait(NULL);
 printf("Child complete");
 exit(0);

  printf("   %d\n",fibo(a));
}


int fibo(int n)
{
 if (n==1 || n==2)
  return 1;
 return fibo(n-1)+fibo(n-2);

}

전 초보라서 이정도 밖에 못하겠네요 여기저기 정보수집해서 해밨는데 에러 투성입니다

문제가 머냐면

fork()를 이용해서 피보나치를 구현하시요인데 문제가 원문이라서

write a c program using the fork() system call that that generates the Fibonacci sequence in the child process.

The number of the sequence will be provided in the command line.

For example,if 5 is provided, the first five numbers in the fibonacci sequence will be output by the Child process.

Because the parent and child processes have their won copies of the data, it will be necessary for the child to output the sequence.

Have the parent invoke the wait() call to wait for the child process to complete before exiting the program.

Perform necessary error checking to ensure that a non-negative number is passed on the command line.

입니다

제발 누가좀 도와주세요 설명이랑 답변좀 부탁드립나 제발






기본적인 fork와 exec를 함수를 이해하셔야합니다.

 

fork는 한프로세스가 두줄기의 제어흐름을 가지게하는 함수라고 볼수있습니다.

 

어떻게 보면 같은 프로세스가 fork함수 뒤로 복제된다고 볼 수 있는데요

 

이 둘을 구분하는 방법은 fork의 return 값을 확인하는 겁니다.

 

fork는 자식프로세스는 0, 부모프로세스는 자식 프로세스 아이디(pid)값을 반환합니다.

 

따라서 if ( pid ...) 식으로 부모와 자식의 일을 분할 할 수 있는 겁니다.

 

근데 저기 소스에 보면 exec 까지 쓰셨더군요.

 

else if (pid==0){
  execlp("/bin/ls","ls",NULL);

 fibo(a); // 이것은 실행되지 않습니다.

     }

exec 함수는 프로세스 이미지를 교체하는 함수입니다.

 

이것이 무슨 소리냐 하면 님의 소스에서 보면 fork로 프로세스가 2개가된 걸 알수있고

2개중 자식 프로세스(pid == 0)은 ls로 대체되는 것입니다. 컴파일 에러가 없다면

런타임에 자식은 ls의 결과물을 출력해 줄 겁니다. exec 는 프로세스의 이미지가 교체 됨으로 전에 있던 프로세스로 다시 돌아가지 않습니다. ( fibo(a)가 실행되지 않아요~ )

 

왜 exec를 쓰셨는지 모르지만 저 line을 지우시고 컴파일 에러잡는걸 거치신 후 실행하시면 원하는 결과가 나올 듯 합니다.


제주삼다수, 2L,... 오뚜기 진라면 매운... 상하목장 유기농 흰... 남양 프렌치카페 카... 고려인삼유통 홍삼 ... 종근당건강 오메가3... 요이치 카링 유무선...