251019

lililllilillll·2025년 10월 19일

개발 일지

목록 보기
329/350

✅ 한 것들


  • 지원서 작성
  • 윤성우의 열혈 TCP/IP 소켓 프로그래밍
  • R&D : Flat kit


📖 윤성우의 열혈 TCP/IP 소켓 프로그래밍


Chapter 11 프로세스간 통신 (Inter Process Communication)

11-1 프로세스간 통신의 기본 개념

파이프

  • 두 프로세스간 통신에 쓰인다
  • 프로세스에 속하지 않고, 소켓처럼 운영체제에 속한다 (fork로 복사 안된다)

pipe()

  • 배열에 파일 디스크립터 2개 담는다
  • 각각 파이프의 출구와 입구로 사용된다
  • 부모가 파이프 만든 후에 디스크립터 하나는 자식 프로세스에게 전달해야 한다
  • 그냥 변수에 저장해두면 입출력 디스크립터 부모 자식 둘 다 갖게된다

파이프 기반의 프로세스간 양방향 통신

int main(int argc, char *argv[])
{
	int fds[2];
	char str1[] = "who are you?";
	char str2[] = "Thank you for your message";
	char buf[BUF_SIZE];
	pid_t pid;

	pipe(fds);
	pid=fork();
	if(pid==0) // 자식 프로세스
	{
		write(fds[1], str1, sizeof(str1));
		sleep(2);
		read(fds[0], buf, BUF_SIZE);
		printf("Child proc output: %s \n", buf);
	}
	else // 부모 프로세스
	{
		read(fds[0], buf, BUF_SIZE);
		printf("Parent proc output: %s \n", buf);
		write(fds[1], str2, sizeof(str2));
		sleep(3);
	}
	return 0;
}

sleep()을 주석처리 해버려서
자식 프로세스가 write()한 후에 안 기다리게 되면
자기가 쓴거 read()로 다시 가져가버린다.

이를 방지하기 위해, 파이프를 두 개 생성할 수 있다.

	pipe(fds1), pipe(fds2);
	pid = fork();
	if(pid==0)
	{
		write(fds1[1], str1, sizeof(str1));
		read(fds2[0], buf, BUF_SIZE);
		printf("Child proc output: %s \n", buf);
	}
	else
	{
		read(fds1[0], buf, BUF_SIZE);
		printf("Parent proc output: %s \n", buf);
		write(fds2[1], str2, sizeof(str2));
		sleep(3);
	}

11-2 프로세스간 통신의 적용

프로세스간 통신은 서버 구현에 직접적 연관은 없다.
운영체제 이해한다는 것에 의의가 있다.

	if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
		error_handling("bind() error");
	if(listen(serv_sock, 5)==-1)
		error_handling("listen() error");

	pipe(fds);
	pid=fork();
	if(pid==0)
	{
		FILE *fp = fopen("echomsg.txt", "wt");
		char msgbuf[BUF_SIZE];
		int i, len;

		for(i=0; i<10; i++)
		{
			len=read(fds[0],msgbuf,BUF_SIZE);
			fwrite((void*)msgbuf, 1, len, fp);
		}
		fclose(fp);
		return 0;
	}
	while(1)
	{
		adr_sz=sizeof(clnt_adr);
		clnt_sock=accept(serv_sock,(struct sockaddr*)&clnt_adr, &adr_sz);
		if(clnt_sock==-1)
			continue;
		else
			puts("new client connected...");

		pid=fork();
		if(pid==0)
		{
			close(serv_sock);
			while((str_len=read(clnt_sock,buf,BUF_SIZE))!=0)
			{
				write(clnt_sock, buf, str_len);
				write(fds[1], buf, str_len);
			}

			close(clnt_sock);
			puts("client disconnected...");
			return 0;
		}
		else
			close(clnt_sock);
	}
	close(serv_sock);

첫 if문 : 파이프로 들어오는 데이터 읽어서 파일에 적는 자식 프로세스 생성.
while문의 if문 : read()의 반환 값이 0일 때까지 파이프에 데이터를 보내는 자식 프로세스 생성



profile
너 정말 **핵심**을 찔렀어

0개의 댓글