程序要求:
子进程读,父进程写,由pipe管道来实现进程间的通信
程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void child_read(int *);
static void father_write(int *, int );
int main(int argc, const char *argv[])
{
pid_t pid;
int pipe_fd[2];
if (pipe(pipe_fd) < 0) //创建pipe管道
{
perror("failed to create pipe");
exit(-1);
}
if ((pid = fork()) < 0)
{
perror("failed to fork pid");
exit(-1);
}
if (pid == 0)
child_read(pipe_fd); //子进程负责读数据
else
father_write(pipe_fd, pid); //父进程负责写数据
return 0;
}
static void child_read(int *pipe_fd)
{
char buf[100];
close(pipe_fd[1]); //子进程负责读数据,因此关闭写端
while (read(pipe_fd[0], buf, sizeof(buf)) > 0) //读数据
{
if (strncmp(buf, "quit", 4) == 0)
exit(0);
printf("read : %s\n", buf);
memset(buf, sizeof(buf), 0);
}
return ;
}
static void father_write(int *pipe_fd, int pid)
{
char buf[100];
close(pipe_fd[0]); //同理,关闭读端
while (1)
{
usleep(500);
printf(">");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = 0;
write(pipe_fd[1], buf, strlen(buf) + 1); //写数据
if (strncmp(buf, "quit", 4) == 0)
break;
memset(buf, sizeof(buf), 0);
}
waitpid(pid, NULL, 0);
return ;
}