#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);
}
}
Linux -- 无名管道pipe单向读写演示实例
最新推荐文章于 2022-09-07 19:52:19 发布