Linux -- 無名管道pipe單向讀寫演示實例

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define QUIT_STR "quit"

int
main(int argc, char *argv[])
{
	int pipefd[2];
	pid_t cpid;
	char buf[100]={0};

	if (pipe(pipefd) == -1) {
	   perror("pipe");
	   exit(EXIT_FAILURE);
	}

	cpid = fork();
	if (cpid == -1) {
	   perror("fork");
	   exit(EXIT_FAILURE);
	}

	if (cpid == 0) {    /* 子進程從無名管道讀 */
	   close(pipefd[1]);    	   /* 關閉未使用的寫端 */

		while(1){
			bzero(buf,100);	//清空緩衝區,緩衝區的值爲0,也就是'\0'的值
			read(pipefd[0], buf, sizeof(buf)) ;
			fprintf(stderr,"In child process -- read:%s\n",buf);	
			if( !strncasecmp(buf,QUIT_STR, strlen(QUIT_STR)) ) { //輸入quit(不區分大小寫),結束
				break;
			}							
		}
		
	   close(pipefd[0]); /*關閉讀端*/
	   _exit(EXIT_SUCCESS);

	} else {            /*父進程從無名管道寫*/
	
	   close(pipefd[0]);          /* 關閉未使用的讀端 */

	   while(1){
		   
		   fprintf(stderr,"In parent process -- write:");	
		   bzero(buf,100);			  
		   fgets(buf, sizeof(buf)-1,stdin);  /*最後一個字符表示字符串結束標誌,防止溢出*/
		   write(pipefd[1], buf,strlen(buf));
			if( !strncasecmp(buf,QUIT_STR, strlen(QUIT_STR)) ) { //輸入quit(不區分大小寫),想要結束
				break;
			}	
			usleep(500);	/*父子進程運行的先後次序不能保證,在這裏延時500us讓進程能有個次序*/	   	   
	   }
	   close(pipefd[1]);          /* 關閉寫端* */
	   wait(NULL);                /* 等待子進程退出 */
	   exit(EXIT_SUCCESS);
	   
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章