做实验的时候写的代码,有问题请指教.
运行的环境:WSL Ubuntu 18.04.4 LTS \n \l
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define ReadEnd 0
#define WriteEnd 1
void report_and_exit(const char* msg) {
perror(msg);
exit(-1); /** failure **/
}
int main() {
int pipe_fd[2];
char w_buffer[100],r_buffer[100];
pid_t cpid;
//创建管道
if (pipe(pipe_fd) < 0)
report_and_exit("pipefd");
for(int i=0;i<2;i++){
if((cpid=fork())==0){
close(pipe_fd[ReadEnd]);
sprintf(w_buffer,"Child %d process is sending message!\n",i+1);
write(pipe_fd[WriteEnd],w_buffer,strlen(w_buffer));
exit(0);
}
else if(cpid>0){ //父进程执行序列
waitpid(cpid,NULL,0); //父子进程同步
printf("pid%d:%d\n",i+1,cpid);
}
}
//不能在循环里就关闭写通道,不然第二个子进程无法向管道写入数据
close(pipe_fd[WriteEnd]);
while(read(pipe_fd[0],r_buffer,sizeof(r_buffer))>0){
printf("%s\n",r_buffer);
}
return 0;
}