一、实现无名管道练习:父进程写入管道,子进程读取管道数据。
#include<myhead.h>
int main(int argc, const char *argv[])
{int fd[2];char buff[1024]="王吕阳,崔庆权别卷了";char s[1024];if(pipe(fd)==-1){perror("pipe");return -1;}pid_t pid = fork();if(pid==0){close(fd[1]);//关闭写端while(1){sleep(1);read(fd[0],s,sizeof(s));printf("展旗善意提醒:%s\n",s);}close(fd[0]);//关闭读端}else if(pid>0){close(fd[0]);//关闭读端while(1){sleep(1);write(fd[1],buff,sizeof(buff));}close(fd[1]);}else{perror("fork");return -1;}return 0;
}
二、有名管道练习实现一遍练习:创建2个子父进程,父进程写入管道1,子进程读取管道2,父进程写入管道2,子进程读取管道1,实现全双工通信。
#include<myhead.h>
int main(int argc, const char *argv[])
{int fd1 = open("./a",O_WRONLY);int fd2 = open("./b",O_RDONLY);char arr[1024];char brr[1024];if(fd1==-1||fd2==-1){perror("open");return -1;}pid_t pid = fork();if(pid>0){while(1){printf("请输入内容:");int res = read(0,arr,sizeof(arr));write(fd1,arr,res);}close(fd1);}else if(pid==0){while(1){int ress = read(fd2,brr,sizeof(brr));if(ress==0){printf("退出\n");break;}write(1,brr,ress);}close(fd2);}else{perror("fork");return -1;}return 0;
}
#include<myhead.h>
int main(int argc, const char *argv[])
{int fd1 = open("./a",O_RDONLY);int fd2 = open("./b",O_WRONLY);char arr[1024];char brr[1024];if(fd1==-1||fd2==-1){perror("open");return -1;}pid_t pid = fork();if(pid>0){while(1){printf("请输入内容:");int ress = read(0,brr,sizeof(brr));write(fd2,brr,ress);}close(fd2);}else if(pid==0){while(1){int res = read(fd1,arr,sizeof(arr));if(res==0){printf("退出\n");break;}write(1,arr,res);}close(fd1);}else{perror("fork");return -1;}return 0;
}
三、进程间通信信号的默认,忽略,捕获实现一遍。
#include<myhead.h>
void a(int b)
{if(b==SIGTSTP){printf("A\n");}
}
int main(int argc, const char *argv[])
{
/* if(signal(SIGINT,SIG_IGN)==SIG_ERR){perror("signal");return -1;}if(signal(SIGINT,SIG_DFL)==SIG_ERR){perror("signal");return -1;}*/if(signal(SIGTSTP,a)==SIG_ERR){perror("signal");return -1;}int k=0;while(1){sleep(1);printf("按k=%d\n",k);k++;}return 0;
}
四、思维导图