10.3作业

#include 
int main(int argc, const char *argv[])
{
	int pipe1[2]={0};
	int pipe2[2]={0};
	if(pipe(pipe1)<0)
	{
		ERR_MSG("pipe1");
		return -1;
	}
	if(pipe(pipe2)<0)
	{
		ERR_MSG("pipe");
	}
	ssize_t res = 0;
	pid_t cpid = fork();
	char buf[128] = "";
	if(cpid > 0){
		while(1){
			close(pipe1[0]);
			close(pipe2[1]);
			printf("父进程请输入:");
			fgets(buf, sizeof(buf), stdin);
			buf[strlen(buf)-1] = 0;

			if(write(pipe1[1], buf, sizeof(buf)) < 0)
			{
				ERR_MSG("write");
				return -1;
			}
			bzero(buf, sizeof(buf));
			res = read(pipe2[0], buf, sizeof(buf));
			if(res < 0){
				ERR_MSG("resd");
				return -1;
			}else if(0 == res){
				printf("读取完毕,切写端关闭\n");
				break;
			}
			printf("父进程接收:%s\n",buf);
		}
		close(pipe1[1]);
		close(pipe2[0]);
	}else if(0 == cpid){
		while(1){
			close(pipe1[1]);
			close(pipe2[0]);
			res = read(pipe1[0], buf, sizeof(buf));
			if(res < 0){
				ERR_MSG("read");
				return -1;
			}else if(0 == res){
				printf("读取完毕,且写端关闭\n");
				break;
			}
			printf("子进程接收:%s\n",buf);
			bzero(buf, sizeof(buf));
			printf("子进程请输入:");
			fgets(buf, sizeof(buf), stdin);
			buf[strlen(buf)-1] = 0;
			if(write(pipe2[1], buf, sizeof(buf)) < 0){
				ERR_MSG("write");
				return -1;
			}
		}
		close(pipe1[0]);
		close(pipe2[1]);
	}
	return 0;
}

你可能感兴趣的:(java,算法,前端)