독서노트: 제4장 파이프와 FIFO(2)

UNIX 네트워크 프로그래밍: 볼륨 2 P38 그림 4-14에서 전이중 파이프의 양방향 통신 능력 테스트
/*P38 fduplex.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[])
{
	int		fd[2], n;
	char	c;
	pid_t	childpid;

	//     
	if (pipe(fd) < 0) {
		fprintf(stderr, "pipe error: %s
", strerror(errno)); exit(1); } //  if ((childpid = fork()) < 0) { fprintf(stderr, "fork error: %s
", strerror(errno)); exit(1); } else if (childpid == 0) { //  sleep(3); //  0 if ((n = read(fd[0], &c, 1)) != 1) { if (n < 0) fprintf(stderr, "read error: %s
", strerror(errno)); fprintf(stderr, "child: read returned %d
", n); exit(1); } printf("child read %c
", c); //  0 if (write(fd[0], "c", 1) != 1) { fprintf(stderr, "write error: %s
", strerror(errno)); exit(1); } exit(0); } //  //  1 if (write(fd[1], "p", 1) != 1){ fprintf(stderr, "write error:%s
", strerror(errno)); exit(1); } //  1 if ((n = read(fd[1], &c, 1)) != 1) { fprintf(stderr, "read error: %s
", strerror(errno)); fprintf(stderr, "parent: read returned %d
", n); exit(1); } printf("parent read %c
", c); exit(0); }

이곳의 듀플렉스 파이프는 두 개의 듀플렉스 파이프로 구성되어 있다.fd[1]에 기록된 데이터는 fd[0]에서만 읽을 수 있고 fd[0]에 기록된 데이터는 fd[1]에서만 읽을 수 있다.
우리는 듀플렉스 파이프를 만들고 포크를 호출해서 부모 프로세스가 문자 p를 쓰고 그 중에서 문자를 읽습니다.하위 프로세스는 파이프에서 문자를 읽은 후 3초 동안 수면을 취하고 문자 c를 씁니다.하위 프로세스 수면은 부모 프로세스의read가 하위 프로세스보다 먼저read를 호출하여 부모 프로세스가 방금 쓴 문자를 읽는지 확인하기 위한 것입니다.
Ubuntu 14.04에서 실행:
$ ./fduplex 
read error: Bad file descriptor
parent: read returned -1
$ child read p
write error: Bad file descriptor

부모 프로세스는 문자 p를 씁니다. 이것은 하위 프로세스에서 읽지만, 이후 부모 프로세스는 fd[1]read에서 중단되고, 하위 프로세스는 fd[0]write로 중단됩니다.
이를 통해 알 수 있듯이 리눅스는 기본적으로 반이중 파이프를 제공한다. (컴파일할 때 다른 옵션을 지정하면 전이중 파이프를 제공할 수 있습니까?)

좋은 웹페이지 즐겨찾기