先放下代码 回来在解释
头文件:
clientinfo.h
1 struct CLIENTINFO{ 2 char myfifo[500]; 3 int leftarg; 4 int rightarg; 5 char op; 6 }; 7 typedef struct CLIENTINFO CLIENTINFO, *CLINTINFOPTR;
client.c
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <fcntl.h> 7 #include <signal.h> 8 #include "clientinfo.h" 9 10 #define FIFO_NAME "/home/levi/chatapplication/data/server_fifo/chat_server_fifo" 11 #define BUFF_SZ 100 12 13 char mypipename[BUFF_SZ]; 14 void handler(int sig){ 15 unlink(mypipename); 16 exit(1); 17 } 18 19 int main(int argc, char const *argv[]) 20 { 21 int res; 22 int fifo_fd, my_fifo; 23 int fd; 24 CLIENTINFO info; 25 char buffer[BUFF_SZ]; 26 27 signal(SIGKILL, handler); 28 signal(SIGINT, handler); 29 signal(SIGTERM, handler); 30 31 if(argc != 4){ 32 printf("Usage: %s op1 operation op2 ", argv[0]); 33 exit(1); 34 } 35 if(access(FIFO_NAME, F_OK) == -1){ 36 printf("Could not open FIFO %s ", FIFO_NAME); 37 exit(EXIT_FAILURE); 38 } 39 fifo_fd = open(FIFO_NAME, O_WRONLY); 40 if(fifo_fd == -1){ 41 printf("Could not open %s for write access ", FIFO_NAME); 42 exit(EXIT_FAILURE); 43 } 44 sprintf(mypipename, "/home/levi/chat_client_%d_fifo", getpid()); 45 res = mkfifo(mypipename, 0777); 46 if(res != 0){ 47 printf("FIFO %s was not created ", buffer); 48 exit(EXIT_FAILURE); 49 } 50 51 my_fifo = open(mypipename, O_RDONLY | O_NONBLOCK); 52 if(my_fifo == -1){ 53 printf("Could not open %s for read only access ", FIFO_NAME); 54 exit(EXIT_FAILURE); 55 } 56 57 strcpy(info.myfifo, mypipename); 58 info.leftarg = atoi(argv[1]); 59 info.op = argv[2][0]; 60 info.rightarg = atoi(argv[3]); 61 62 write(fifo_fd, &info, sizeof(CLIENTINFO)); 63 close(fifo_fd); 64 65 memset(buffer, '