作业内容
- 要求AB进程做通信:
A进程发送一句话,B进程接收打印
然后B进程发送给A进程一句话,A进程接收打印
重复1,2步骤,直到A进程或者B进程收到quit,退出AB进程; - 捕获2号、3号、20号信号
1. A、B进程间通信
进程A代码部分
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo1",0777) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo1");
return -1;
}
}
if(mkfifo("./myfifo2",0777) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo2");
return -1;
}
}
int fd1 = open("./myfifo1",O_WRONLY);
if(fd1 < 0)
{
perror("open");
return -1;
}
int fd2 = open("./myfifo2",O_RDONLY);
if(fd2 < 0)
{
perror("open");
return -1;
}
char buf1[128] = "";
char buf2[128] = "";
ssize_t res = 0;
while(1)
{
printf("A is writing: ");
fgets(buf1,sizeof(buf1),stdin);
buf1[strlen(buf1)-1] = 0;
if(write(fd1,buf1,sizeof(buf1)) < 0)
{
perror("write");
return -1;
}
if(strcasecmp(buf1,"quit") == 0)
break;
bzero(buf2,sizeof(buf2));
res = read(fd2,buf2,sizeof(buf2));
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res)
{
printf("B has exited\n");
break;
}
printf("A receive a message from B: %s\n",buf2);
}
close(fd1);
close(fd2);
return 0;
}
进程B代码部分
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo1",0777) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo1");
return -1;
}
}
if(mkfifo("./myfifo2",0777) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo2");
return -1;
}
}
int fd1 = open("./myfifo1",O_RDONLY);
if(fd1 < 0)
{
perror("open");
return -1;
}
int fd2 = open("./myfifo2",O_WRONLY);
if(fd2 < 0)
{
perror("open");
return -1;
}
char buf1[128] = "";
char buf2[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf1,sizeof(buf1));
res = read(fd1,buf1,sizeof(buf1));
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res)
{
printf("A has exited\n");
break;
}
printf("B receive a message from A: %s\n",buf1);
printf("B is writing: ");
fgets(buf2,sizeof(buf2),stdin);
buf2[strlen(buf2)-1] = 0;
if(write(fd2,buf2,sizeof(buf2)) < 0)
{
perror("write");
return -1;
}
if(strcasecmp(buf2,"quit") == 0)
break;
}
close(fd1);
close(fd2);
return 0;
}
运行结果
2.捕获信号
代码部分
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
typedef void (*sighandler_t)(int);
void handler_2(int sig)
{
printf("This is SIGINT: %d\n",sig);
}
void handler_3(int sig)
{
printf("This is SIGQUIT: %d\n",sig);
}
void handler_20(int sig)
{
printf("This is SIGTSTP: %d\n",sig);
}
int main(int argc, const char *argv[])
{
sighandler_t s1 = signal(2,handler_2);
if(SIG_ERR == s1)
{
perror("signal");
return -1;
}
sighandler_t s2 = signal(3,handler_3);
if(SIG_ERR == s2)
{
perror("signal");
return -1;
}
sighandler_t s3 = signal(20,handler_20);
if(SIG_ERR == s3)
{
perror("signal");
return -1;
}
while(1);
return 0;
}
运行结果