int pipe(int fd[2])
管道通信为半双工通信,用于父子进程之间。
管道创建成功返回0,出错返回-1.fd[0]为读打开,fd[1]为写打开。
#include
#include
#include
#include
#include
#include
main()
{
int pipe_fd[2];
pid_t pid;
char r_buf[25];
char w_buf[25];
char *p_wbuf;
int r_num;
memset(r_buf,0,sizeof(r_buf));
memset(w_buf,0,sizeof(w_buf));
p_wbuf=w_buf;
if(pipe(pipe_fd)<0)
{
printf("pipe create error\n");
return -1;
}
if((pid=fork())==0)
{
close(pipe_fd[1]);
sleep(3);
r_num=read(pipe_fd[0],r_buf,25);
printf("read num is %d the data read from the pipe is %s\n",r_num,r_buf);
close(pipe_fd[0]);
exit(0);
}
else if(pid>0)
{
close(pipe_fd[0]);
strcpy(w_buf,"parents tell to child");
if(write(pipe_fd[1],w_buf,25)!=-1)
printf("parent write over\n");
close(pipe_fd[1]);
printf("parent close fd[1] over\n");
sleep(5);
}
}
//父进程创建一个子进程,父进程发送消息,子进程接受。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define exit_err(str) do{ perror(str);exit(1);} while(0);
int ptc[2], ctp[2];
void initproc() //初始化,创建两个管道
{
if(-1 == pipe(ptc))
exit_err("pipe ptc");
if(-1 == pipe(ctp))
exit_err("pipe ctp");
}
void waitchild() //读管道ctp
{
int pid;
if (-1 == read(ctp[0], &pid, 1))
exit_err("read1");
printf("parent has reveived the information\n");
printf("print the parent_pid recieved from child %d\n",pid);
}
void waitparent() //读管道ptc
{
int pid;
if (-1 == read(ptc[0], &pid, 1))
exit_err("read2");
printf("child has reveived the information\n");
printf("print the child_pid recieved from parent %d\n",pid);
}
void inforchild(int pid) //向管道ptc中写入子进程id
{
if (-1 == write(ptc[1],&pid, 1))
exit_err("write2");
printf("parent has informed the child\n\n");
}
void inforparent(int pid) //向管道cpt中写入父进程id
{
if (-1 == write(ctp[1],&pid, 1))
exit_err("write1");
printf("child has informed the parent\n\n");
}
int main(void)
{
int i = 1;
pid_t pid;
initproc();
if((pid = fork())<0)
exit_err("fork");
if (pid == 0) {
do {
waitparent();
printf("child process is going\n");
inforparent(getppid()); //向管道cpt中写入父进程id
} while (i--);
} else {
do {
printf("parent process is going\n");
inforchild(pid); //向管道ptc中写入子进程id
waitchild();
}
while (i--);
}
return 0;
}
//父子进程通过管道,同步向屏幕输出语句
阅读(732) | 评论(0) | 转发(0) |