1)要求AB进程做通信
-
A进程发送一句话,B进程接收打印
-
然后B进程发送给A进程一句话,A进程接收打印
-
重复1,2步骤,直到A进程或者B进程收到quit,退出AB进程;
进程A:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./myfifo1",0777)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./myfifo2",0777)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
int fd1 =open("./myfifo1",O_WRONLY);
int fd2 =open("./myfifo2",O_RDONLY);
if(fd1<0|fd2<0)
{
perror("open");
return -1;
}
printf("open success\n");
char buf[128]="";
char str[128]="";
while(1)
{
bzero(buf,sizeof(buf));
printf("请输入A进程发送的信息:");
scanf("%s",buf);
if(write(fd1,buf,sizeof(buf))<0)
{
perror("write");
return -1;
}
if(strcasecmp(buf,"quit")==0)
break;
sleep(1);
bzero(str,sizeof(str));
read(fd2,str,sizeof(str));
printf("A进程收到的信息为:%s\n",str);
if(strcasecmp(str,"quit")==0)
break;
}
close(fd1);
close(fd2);
return 0;
}
B进程:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./myfifo",0777)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./myfifo2",0777)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
int fd1=open("./myfifo1",O_RDONLY);
int fd2 =open("./myfifo2",O_WRONLY);
if(fd1<0|fd2<0)
{
perror("open");
return -1;
}
printf("open success\n");
char buf[128]="";
char str[128]="";
ssize_t res =0;
while(1)
{
bzero(buf,sizeof(buf));
res=read(fd1,buf,sizeof(buf));
printf("B进程收到的信息为:%s\n",buf);
if(strcasecmp(buf,"quit")==0)
break;
if(res<0)
{
perror("read");
return -1;
}
bzero(str,sizeof(str));
printf("请输入B进程发送的信息:");
scanf("%s",str);
if(write(fd2,str,sizeof(str))<0)
{
perror("write");
return -1;
}
if(strcasecmp(str,"quit")==0)
break;
}
close(fd1);
close(fd2);
return 0;
}
2)捕获2)3)20)号信号
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
typedef void (*sighandler_t)(int);
//新的处理函数
void handler2(int sig)
{
printf("this is handler%d\n", sig);
}
void handler3(int sig)
{
printf("this is handler%d\n", sig);
}
void handler20(int sig)
{
printf("this is handler%d\n", sig);
}
int main(int argc, const char *argv[])
{
//捕获2号信号SIGINT
sighandler_t s2 = signal(2, handler2);
if(SIG_ERR == s2)
{
perror("signal");
return -1;
}
printf("%p %d\n", s2, __LINE__); //默认处理函数的首地址获取不到,所以打印NULL;
sighandler_t s3 = signal(3, handler3);
if(SIG_ERR == s3)
{
perror("signal");
return -1;
}
printf("%p %d\n", s3, __LINE__);
sighandler_t s20 = signal(20, handler20);
if(SIG_ERR == s20)
{
perror("signal");
return -1;
}
printf("%p %d\n", s20, __LINE__);
while(1)
{
printf("this is main\n");
sleep(1);
}
return 0;
}