본문 바로가기
운영체제/xv6

xv6 Lab: Utilities (2) pingpong

by JaeminRyu 2022. 8. 31.
728x90

이 문제는 MIT의 xv6 수업에 출처가 있습니다.

출처 : Lab: Xv6 and Unix utilities (mit.edu)

Write a program that uses UNIX system calls to ''ping-pong'' a byte between two processes over a pair of pipes, one for each direction.
The parent should send a byte to the child; the child should print "<pid>: received ping", where <pid> is its process ID, write the byte on the pipe to the parent, and exit; the parent should read the byte from the child, print "<pid>: received pong", and exit.

child process를 생성한 뒤 pipe를 이용하여 parent process와 통신을 시키는 문제

먼저 parent가 child에게 ping이라는 문자열을 전송한 뒤, child는 이것을 읽고 <pid> : recived ping을 출력한다.

그 후 child가 parent에게 pong이라는 문자열을 전송한 뒤, parent는 이것을 읽고 <pid> : recived pong을 출력한다.

 

사전 지식

1.fork()함수

child process를 생성하는 함수이다.

return 값으로 parent process는 자신의 PID를, child process는 0을 갖는다

 

2.pipe()함수

파이프 라인은 pipe()함수로 생성한다.

pipe(p) 함수의 인수 p에서 p[0]은 파이프의 읽기 디스크립터, p[1]은 쓰기 디스크립터이다.

따라서 p[1]에 전달하고 싶은 정보를 적은 뒤 p[0]에서 읽어오면 된다.

 

 

 

 

Solution

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(){
	int p[2];	//파이프 변수
    char buf[5];
    int pid,satus;
    
    pipe(p):	//파이프 열기
    
    pid = fork();
    
    if(pid == 0){	//child process
    	read(p[0],recv,4);			//pipe 읽기
        close(p[0]);				//읽기 라인 닫기
        printf("%d: received %s\n",getpid(), recv);
        
        write(p[1],"pong",4);		//pipe에 pong 기록
        close(p[1]);				//쓰기 라인 닫기
    }
    else{			//parent process
    	write(p[1],"ping",4);		//pipe에 ping 기록
        close(p[1]);				//쓰기 라인 닫기
        
        wait()						//child가 종료될 때 까지 (write 할 때 까지) 대기
        read(p[0],recv,4);			//pipe 읽기
        printf("%d: recived %s\n",getpid(),recv);
        close(p[0]);				//읽기 라인 닫기
    }  
}

'운영체제 > xv6' 카테고리의 다른 글

xv6 Lab: Utilities (5) xargs  (0) 2022.09.03
xv6 Lab: Utilities (4) find  (0) 2022.09.02
xv6 Lab: Utilities (3) primes  (0) 2022.09.01
xv6 Lab: Utilities (1) sleep  (0) 2022.08.31