1. 要求AB进程做通信
1. A进程发送一句话,B进程接收打印
2. 然后B进程发送给A进程一句话,A进程接收打印
3. 重复1,2步骤,直到A进程或者B进程收到quit,退出AB进程;
2. 捕获2)3)20)号信号
A进程的代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./myfifo1",0777) < 0) // 创建有名管道1
{
printf("errno = %d\n",errno);
if(errno != 17)
{
perror("mkfifo1");
return -1;
}
printf("mkfifo1 success\n");
}
if(mkfifo("./myfifo2",0777) < 0) // 创建有名管道2
{
printf("errno = %d\n",errno);
if(errno != 17)
{
perror("mkfifo2");
return -1;
}
printf("mkfifo2 success\n");
}
int fd = open("./myfifo1", O_WRONLY); //以只写的方式打开
if(fd < 0)
{
perror("open");
return -1;
}
printf("open writeonly success\n");
char buf[128] = "";
while(1)
{
printf("请输入>>>");
fgets(buf, sizeof(buf), stdin); //输入
buf[strlen(buf)-1] = 0;
if(write(fd, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
if (strcmp(buf,"quit")==0)
{
printf("对方已退出\n");
break;
}
printf("write success\n");
}
int gf = open("./myfifo2", O_RDONLY); // 以只读的方式打开
if(fd < 0)
{
perror("open");
return -1;
}
printf("open readonly success\n");
char str[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf, sizeof(buf));
res = read(fd, buf, sizeof(buf)); //读取
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res) //没有写端
{
printf("对方进程退出\n");
break;
}
}
return 0;
}
B进程的代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
int gf = open("./myfifo2",O_WRONLY); // 以只写的方式打开
if (gf<0)
{
perror("open");
return -1;
}
int fd = open("./myfifo1",O_RDONLY); //以只读的方式打开
if (fd<0)
{
perror("open");
return -1;
}
char ssd[128]="";
char sst[128]="";
ssize_t res = 0;
while(1)
{
bzero(ssd, sizeof(ssd));
res = read(fd, ssd, sizeof(ssd));//读取
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res)
{
printf("对方进程退出\n");
break;
}
printf("read success :%ld : %s\n", res, ssd);
bzero(sst, sizeof(sst));
printf("子进程说>>>");
fgets(sst, sizeof(sst), stdin);
sst[strlen(sst)-1] = 0;
if(write(gf, sst, sizeof(sst)) < 0) //写入
{
perror("write");
return -1;
}
if (strcmp(sst,"quit")==0)
{
break;
}
}
return 0;
}
捕获2)3)20)号信号:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
typedef void (*sighandler_t)(int);
void handler(int sig)
{
printf("handler is this %d\n",sig);
}
int main(int argc, const char *argv[])
{
sighandler_t s1= signal(2,handler);
if (SIG_ERR==s1)
{
perror("signal");
return -1;
}
sighandler_t s2= signal(3,handler);
if (SIG_ERR==s2)
{
perror("signal");
return -1;
}
sighandler_t s3= signal(20,handler);
if (SIG_ERR==s3)
{
perror("signal");
return -1;
}
while(1)
{
printf("singel\n");
sleep(1);
}
return 0;
}