#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pipe_fd[2];
pid_t pid;
char buf_r[100];
char* p_wbuf;
int r_num;
memset(buf_r,0,sizeof(buf_r));
if(pipe(pipe_fd)<0) //创建管道,如果系统调用成功,管道的两个文件描述符将赋予数组pipe_fd[2].
{
printf("pipe create error\n");
return -1;
}
if((pid=fork())==0) //将fork()进程的id赋给pid,并判断如果为0,则在子进程中。
{
printf("\n");
close(pipe_fd[1]); //关闭子进程管道写入端,防止误操作。
sleep(2);
if((r_num=read(pipe_fd[0],buf_r,100))>0)//从管道读入端读取内容到buf_r数组地址中,读取大小为100字节。并将read()函数返回值(读取的字节数)赋予变量r_num。
{
printf( "%d numbers read from the pipe is %s\n",r_num,buf_r);//将读到的内容打印到屏幕
}
close(pipe_fd[0]); //关闭管道的读出端,习惯关闭,防止误操作。
exit(0);
}
else if(pid>0) //如果fork()进程大于0,则位于父进程中。
{
close(pipe_fd[0]);关闭父进程中管道读出端。
if(write(pipe_fd[1],"Hello",5)!=-1) //将Hello写入管道中,如果成功,返回写入文件的字节数;如果失败,返回-1.
printf("parent write1 success!\n");
if(write(pipe_fd[1]," Pipe",5)!=-1) //将Pipe写入管道中,如果成功,返回写入文件的字节数;如果失败,返回-1.
printf("parent write2 success!\n");
close(pipe_fd[1]);//关闭父进程写入端
sleep(3);
waitpid(pid,NULL,0);/*等待进程号为pid的子进程结束*/
exit(0);
}
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pipe_fd[2];
pid_t pid;
char buf_r[100];
char* p_wbuf;
int r_num;
memset(buf_r,0,sizeof(buf_r));
if(pipe(pipe_fd)<0) //创建管道,如果系统调用成功,管道的两个文件描述符将赋予数组pipe_fd[2].
{
printf("pipe create error\n");
return -1;
}
if((pid=fork())==0) //将fork()进程的id赋给pid,并判断如果为0,则在子进程中。
{
printf("\n");
close(pipe_fd[1]); //关闭子进程管道写入端,防止误操作。
sleep(2);
if((r_num=read(pipe_fd[0],buf_r,100))>0)//从管道读入端读取内容到buf_r数组地址中,读取大小为100字节。并将read()函数返回值(读取的字节数)赋予变量r_num。
{
printf( "%d numbers read from the pipe is %s\n",r_num,buf_r);//将读到的内容打印到屏幕
}
close(pipe_fd[0]); //关闭管道的读出端,习惯关闭,防止误操作。
exit(0);
}
else if(pid>0) //如果fork()进程大于0,则位于父进程中。
{
close(pipe_fd[0]);关闭父进程中管道读出端。
if(write(pipe_fd[1],"Hello",5)!=-1) //将Hello写入管道中,如果成功,返回写入文件的字节数;如果失败,返回-1.
printf("parent write1 success!\n");
if(write(pipe_fd[1]," Pipe",5)!=-1) //将Pipe写入管道中,如果成功,返回写入文件的字节数;如果失败,返回-1.
printf("parent write2 success!\n");
close(pipe_fd[1]);//关闭父进程写入端
sleep(3);
waitpid(pid,NULL,0);/*等待进程号为pid的子进程结束*/
exit(0);
}
}
***************************************************
。waitpid函数有三个参数:pid和指向返回状态所在单元的指针和一个用来指定可选项的标识符。如果pid为-1 ,waitpid就等待任何一个子进程,如果pid>0,就是等待pid指定的那个进程结束,参数pid还存在另外的两种可能pid为0,就是等待与调用者在同一个进程组中的任意子进程。最后pid<-1 waitpid就是由pid的绝对值指定的进程组中任意一个子进程.waitpid的参数options是一个或多个标致符按位“或”的结果,即使子进程的状态不是立刻可用的,选项WNOHANG也会使waitpid返回,选项WUNTRACED会使waitpid报告已经被停止的未报告的子进程的状态。
以上为从视频教程中截取的代码加上自己所理解的注解,如果有哪里不对,恳请指正。
新手共勉!
254

被折叠的 条评论
为什么被折叠?



