创建AB进程,要求用B进程杀死A进程
A进程代码
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./fifo", 0777)<0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
printf("创建成功\n");
}
int pf=open("./fifo", O_WRONLY);
if(pf<0)
{
perror("open");
return -1;
}
pid_t pid=getpid();
write(pf,&pid, sizeof(pid));
printf("写入成功\n");
while(1)
{
printf("只是A进程\n");
sleep(1);
}
close(pf);
return 0;
}
B进程代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<signal.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, const char *argv[])
{
printf("这是B进程\n");
if(mkfifo("./fifo", 0777)<0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
printf("创建成功\n");
}
int mp=open("./fifo", O_RDONLY);
if(mp<0)
{
perror("open");
return -1;
}
pid_t pid;
char c;
read(mp,&pid, sizeof(pid));
printf("读取成功\n");
printf("请输入是否杀死A进程Y/N: ");
scanf("%c", &c);
getchar();
kill(pid, 9);
close(mp);
return 0;
}
要求实现AB进程对话:
1)A进程发送一句话,B进程接收后打印;
2)B进程接着再发送一句话,A进程接收打印;
3)重复上述步骤,当A进程或者B进程接收到quit后退出AB进程。
AJ进程
#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[])
{
int res;
if(mkfifo("./fifo", 0777)<0);
{
if(17!=errno)
{
perror("mkfifo");
return -1;
}
}
printf("创建成功\n");
int p;
p=open("./fifo", O_WRONLY);
if(p<0)
{
perror("open");
return -1;
}
char str[128]="";
ssize_t s;
while(1)
{
printf("请输入》》");
fgets(str, sizeof(str), stdin);
str[strlen(str)-1]='\0';
s=write(p, str, sizeof(str));
if(s<0)
{
perror("write");
return -1;
}
printf("输入成功\n");
if(strcmp(str,"quit")==0)
{
break;
}
}
close(p);
return 0;
}
B进程
#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[])
{
int res;
if(mkfifo("./fifo", 0777)<0);
{
if(17!=errno)
{
perror("mkfifo");
return -1;
}
}
printf("创建成功\n");
int p;
p=open("./fifo", O_RDONLY);
if(p<0)
{
perror("open");
return -1;
}
char str[128]="";
ssize_t s;
while(1)
{
s=read(p, str, sizeof(str));
if(s<0)
{
perror("read");
return -1;
}
else if(0==s)
{
break;
}
printf("%s\n", str);
}
close(p);
return 0;
}