파이프
pipe()
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);
}
프로세스간 통신은 서버 구현에 직접적 연관은 없다.
운영체제 이해한다는 것에 의의가 있다.
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일 때까지 파이프에 데이터를 보내는 자식 프로세스 생성