利用C语言写一个程序实现两个进程间进行管道通信

利用C语言写一个程序实现两个进程间进行管道通信,其中一个进程向管道中写入“AHUT”,另一进程读取管道中数据并打印到显示器上。

第1个回答  2016-06-30
#include <stdio.h>

#include <stdlib.h>

#include <errno.h>

#include <string.h>

#define N 10

#define MAX 100

int child_read_pipe(int fd)

{

char buf[N];

int n = 0;

while(1)

{

n = read(fd,buf,sizeof(buf));

buf[n] = '\0';

printf("Read %d bytes : %s.\n",n,buf);

if(strncmp(buf,"quit",4) == 0)

break;

}

return 0;

}

int father_write_pipe(int fd)

{

char buf[MAX] = {0};

while(1)

{

printf(">");

fgets(buf,sizeof(buf),stdin);

buf[strlen(buf)-1] = '\0';

write(fd,buf,strlen(buf));

usleep(500);

if(strncmp(buf,"quit",4) == 0)

break;

}

return 0;

}

int main()

{

int pid;

int fd[2];

if(pipe(fd) < 0)

{

perror("Fail to pipe");

exit(EXIT_FAILURE);

}

if((pid = fork()) < 0)

{

perror("Fail to fork");

exit(EXIT_FAILURE);

}else if(pid == 0){

close(fd[1]);

child_read_pipe(fd[0]);

}else{

close(fd[0]);

father_write_pipe(fd[1]);

}

exit(EXIT_SUCCESS);

}追问

不对吧

不对吧

追答

这不是你要的进程间管道通信?一个写入一大打印出来?

本回答被提问者和网友采纳
相似回答