1、三角形/长方形面积
#include <allhead.h>
int main(int argc, const char *argv[])
{
double data[3]={0};
double s=0;
while(1)
{
read(3,data,24);
if(data[2]==0.0)
{
s = data[0]*data[1];
printf("长方形的面积为:%g\n",s);
}
else
{
double a=data[0];
double b=data[1];
double c=data[2];
double p=(a+b+c)/2;
s = sqrt(p*(p-a)*(p-b)*(p-c));
printf("三角形的面积为:%g\n",s);
}
}
return 0;
}
#include <allhead.h>
int main(int argc, const char *argv[])
{
int pipefd[2]={0};
pipe(pipefd);
int res = fork();
if(res>0)
{
while(1)
{
double data[3]={0};
printf("请输入三角形的三边或长方形的长宽:");
scanf("%lf %lf %lf",&data[0],&data[1],&data[2]);
while(getchar()!=10);
write(pipefd[1],data,24);
sleep(1);
}
}
else if(res==0)
{
execl("./2","2","3",NULL);
}
return 0;
}
2、两个终端聊天
#include <allhead.h>
int main(int argc, const char *argv[])
{
//开两条管道
char myfifo1[32] = "./myfifo1";
int res1 = access(myfifo1,F_OK);
if(res1 == -1)
{
mkfifo(myfifo1,0666);
}
char myfifo2[32] = "./myfifo2";
int res2 = access(myfifo2,F_OK);
if(res2 == -1)
{
mkfifo(myfifo2,0666);
}
//管道打开顺序保持一致
int rd = open("myfifo1",O_RDONLY);
int wd = open("myfifo2",O_WRONLY | O_TRUNC);
char buf[256] ="";
int fo = fork();
if(fo>0)
{
//父进程负责写
while(1)
{
memset(buf,0,sizeof(buf));
printf("\033[1;32;10mUSR2:\033[0m");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(wd,buf,sizeof(buf));
}
exit(0);
}
else if(fo==0)
{
//子进程负责读
while(1)
{
bzero(buf,sizeof(buf));
read(rd,buf,sizeof(buf));
printf("\033[1;31;10mUSR1:\033[0m%s\n",buf);
}
exit(0);
}
close(rd);
close(wd);
return 0;
}