10.3作业

#include 
#include 
#include 
#include 
/*
 * function:    父子间通信,要求如下:父进程发送一句话,子进程接收后打印,然后子进程再给父进程发送一句话,父进程接收打印
 * @param [ in] 
 * @param [out] 
 * @return      
 */
int main(int argc, const char *argv[])
{
	//创建无名管道
	int pfd1[2] = {0};
	int pfd2[2] = {0};
	if(pipe(pfd1) < 0)
	{
		perror("pipe1");
		return -1;
	}
	if(pipe(pfd2) < 0)
	{
		perror("pipe1");
		return -1;
	}
	pid_t cpid = fork();
	if(cpid>0){
		//父进程
		char buf[128]="";
		while(1){
			bzero(buf,sizeof(buf));
			fgets(buf, sizeof(buf), stdin);
			//fgets会获取\n,且在获取\n后会停止,将\n修改成\0
			buf[strlen(buf)-1] = '\0';

			if(write(pfd1[1], buf, sizeof(buf)) < 0)
			{
				perror("write");
				return -1;
			}
			printf("写入成功\n");

			int res=read(pfd2[0], buf, sizeof(buf));
			if(res < 0)
			{
				perror("read");
				return -1;
			}
			else if(0 == res)
			{
				printf("父进程数据读取完毕,且写端关闭\n");
				break;
			}
			printf("父进程端:res=%d buf=%s\n", res, buf);
		}
	}else if(cpid==0){
		//子进程
		char buf[128]="";
		while(1){
			bzero(buf,sizeof(buf));
			int res=read(pfd1[0], buf, sizeof(buf));
			if(res < 0)
			{
				perror("read");
				return -1;
			}
			else if(0 == res)
			{
				printf("子进程数据读取完毕,且写端关闭\n");
				break;
			}
			printf("子进程端:res=%d buf=%s\n", res, buf);

			strcat(buf,"----recvived");
			if(write(pfd2[1], buf, sizeof(buf)) < 0)
			{
				perror("write");
				return -1;
			}
			printf("子进程写入成功\n");
		}

	}
	return 0;
}

运行结果

10.3作业_第1张图片

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