我想使用c创建单边聊天应用程序,当读者(客户端)按下Ctrl + c时,应该关闭编写器(服务器)。但问题仍然是我无法弄清楚当读者按下Ctrl时如何向编写器发送信号+ C
请对此提出任何建议......
这是读者端代码:
#include<fcntl.h>
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<signal.h>
#define max 1990
int fu;
void sigHadeler();
int main(){
struct stat sb;
int fd;
char* fifo="/home/man/shellScript/fifo";
char buf[max];
struct sigaction new_action, old_action;
new_action.sa_handler = sigHadeler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
if( sigaction (SIGINT, NULL, &old_action) == -1)
perror("Failed to retrieve old handle"); /Ctrl + C */
if( sigaction (SIGINT, &new_action, NULL) == -1)/* set the new action */
("Failed to set new Handle");
printf("Start conversation....\n");
while(1){
while(1){
stat(fifo,&sb);
if((sb.st_mode & S_IFMT)==S_IFIFO){
fd=open(fifo,O_RDONLY);
int re =read(fd,buf,max);
buf[re]='\0';
printf("read: %s\n",buf);
close(fd);
break;
}
}
}
return 0;
}
void sigHadeler(){
char* fifo="/home/man/shellScript/fifo";
printf("What have you done \n");
write(fu,"0",strlen("0"));
close(fu);
unlink(fifo);
exit(1);
}
这是作家方代码:
#include<fcntl.h>
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<signal.h>
#define max 1990
int main(){
int fd;
char* input;
input = malloc(sizeof(char)*1000);
char* fifo="/home/man/shellScript/fifo";
printf("Enter string :");
struct stat sb;
mkfifo(fifo,0666);
while(1){
printf("Writing..\n");
fgets(input,max,stdin);
input[strlen(input)-1]='\0';
fd=open(fifo,O_WRONLY| O_NONBLOCK);
if(fd<=0){printf("Reader is closed or no readers ...\n");
exit(1);
}
write(fd,input,strlen(input));
close(fd);
while(1){
stat(fifo,&sb);
if((sb.st_mode & S_IFMT)==S_IFIFO){
close(fd);
}
break;
}
}
unlink(fifo);
return 0;
}