作业10.3

#include
int main(int argc, const char *argv[])
{
	pid_t fd=fork();
	int pfd1[2]={0};
	int pfd2[2]={0};
	if(pipe(pfd1)<0)
	{
		ERR_MSG("pipe");
		return -1;
	}
	if(pipe(pfd2)<0)
	{
		ERR_MSG("pipe");
		return -1;
	}

	if(fd>0)
	{
		char buf[128]="";
		while(1)
		{
			bzero(buf,sizeof(buf));
			printf("father : please enter >>> ");
			fgets(buf,sizeof(buf),stdin);
			buf[strlen(buf)-1]=0;
			if(write(pfd1[1],buf,sizeof(buf))<0)
			{
				ERR_MSG("write");
				return -1;
			}
			printf("write success\n");
			bzero(buf,sizeof(buf));
			int res=read(pfd2[0],buf,sizeof(buf));
			if(res<0)
			{
				ERR_MSG("read");
				return 1;
			}
			if(res==0)
			{
				printf("write is null \n");
				break;
			}
			printf("father get : %s\n",buf);
		}
	}
	else if(fd == 0 )
	{
		char buf[128]="";
		while(1)
		{
			bzero(buf,sizeof(buf));
			int res=read(pfd1[0],buf,sizeof(buf));
			if(res<0)
			{
				ERR_MSG("read");
				return 1;
			}
			if(res==0)
			{
				printf("write is null \n");
				break;
			}
			printf("child get : %s\n",buf);
			bzero(buf,sizeof(buf));
			printf("child : please enter >>> ");
			fgets(buf,sizeof(buf),stdin);
			buf[strlen(buf)-1]=0;
			if(write(pfd2[1],buf,sizeof(buf))<0)
			{
				ERR_MSG("write");
				return -1;
			}
			printf("write success\n");
		}
	}
	return 0;
}

你可能感兴趣的:(c语言)