无名管道
#include<myhead.h>
int main(int argc, const char *argv[])
{
int pipfd[2];
char buff[1024]="hello world";
char s[1024];
if(pipe(pipfd)==-1){
perror("pipe");
return -1;
}
int pid=fork();
if(pid==-1){
perror("fork");
return -1;
}
if(pid == 0){
close(pipfd[1]);
sleep(1);
while(1){
int res=read(pipfd[0],s,sizeof(s));
if(strcmp("#",s)==0){
puts("程序结束");
return -1;
}
printf("父亲数据为:%s\n",s);
}
close(pipfd[0]);
}else if(pid>0){
close(pipfd[0]);
int i=0;
while(1){
usleep(100);
printf("父亲发送数据>>");
scanf("%s",buff);
write(pipfd[1],buff,sizeof buff);
if(strcmp(buff,"#")==0){
puts("退出");
break;
}
}
close(pipfd[1]);
wait(&pid);
}
return 0;
}
斗地主改良版
#include<myhead.h>
void handler(int sig){
if(sig==SIGALRM){
printf("系统自动帮你出牌\n");
printf("请输入你要出的牌\n");
alarm(5);
}
}
int main(int argc, const char *argv[])
{
if(signal(SIGALRM,handler)==SIG_ERR){
perror("signal");
return -1;
}
char ch;
while(1){
alarm(5);
printf("输入你要出的牌");
scanf("%c",&ch);
getchar();
printf("你出的是%c\n",ch);
}
return 0;
}
ubu