国庆作业day4

#include 
int main(int argc, const char *argv[])
{
	//创建无名管道
	int pfd[2] = {0};
	int pfd1[2] = {0};
	if(pipe(pfd) < 0){
		ERR_MSG("pipe");
		return -1;
	}
	if(pipe(pfd1) < 0){
		ERR_MSG("pipe");
		return -1;
	}
	char s[128] = "";
	ssize_t res = 0;
	pid_t cpid = fork();
	if(cpid > 0){
		while(1){
			close(pfd[0]);
			close(pfd1[1]);
			printf("父进程请输入:");
			fgets(s, sizeof(s), stdin);
			s[strlen(s)-1] = 0;

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

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