ArtHell | c1d49a8 | 2016-05-17 00:41:50 +0300 | [diff] [blame] | 1 | #include "Server.h" |
| 2 | |
| 3 | #ifndef _MSC_VER |
| 4 | void handler(int snum) { |
| 5 | |
| 6 | if (snum == SIGUSR1) { |
| 7 | Recieve_message(); |
| 8 | kill(pnum, SIGUSR1); |
| 9 | } else if (snum == SIGUSR2) { |
| 10 | close(fd); |
| 11 | remove(NAMEDPIPE_NAME); |
| 12 | exit(0); |
| 13 | } |
| 14 | } |
| 15 | #endif |
| 16 | |
| 17 | int main(int argc, char *argv[]) { |
| 18 | |
| 19 | cout << "Now run client program." << endl; |
| 20 | |
| 21 | #ifdef _MSC_VER |
| 22 | |
| 23 | HANDLE hEvent; |
| 24 | hEvent = CreateEvent(NULL, FALSE, FALSE, SYNC_EVENT); |
| 25 | |
| 26 | hNamedPipe = CreateNamedPipeA( |
| 27 | lpszPipeName, |
| 28 | PIPE_ACCESS_DUPLEX, |
| 29 | PIPE_TYPE_MESSAGE | |
| 30 | PIPE_READMODE_MESSAGE | |
| 31 | PIPE_WAIT, |
| 32 | PIPE_UNLIMITED_INSTANCES, |
| 33 | BUF_SIZE, |
| 34 | BUF_SIZE, |
| 35 | 5000, |
| 36 | NULL); |
| 37 | |
| 38 | if (hNamedPipe == INVALID_HANDLE_VALUE) { |
| 39 | perror("CreateNamedPipe"); |
| 40 | return 1; |
| 41 | } |
| 42 | |
| 43 | if (!ConnectNamedPipe(hNamedPipe, NULL)) { |
| 44 | perror("ConnectNamedPipe"); |
| 45 | } |
| 46 | |
| 47 | #else |
| 48 | |
| 49 | struct sigaction act; |
| 50 | memset(&act, 0, sizeof(act)); |
| 51 | act.sa_handler = handler; |
| 52 | sigset_t set; |
| 53 | sigemptyset(&set); |
| 54 | sigaddset(&set, SIGUSR1); |
| 55 | sigaddset(&set, SIGUSR2); |
| 56 | act.sa_mask = set; |
| 57 | sigaction(SIGUSR1, &act, NULL); |
| 58 | sigaction(SIGUSR2, &act, NULL); |
| 59 | cout << "Server pid is " << getpid() << endl; |
| 60 | |
| 61 | cout << " Client pid: "; |
| 62 | cin >> pnum; |
| 63 | |
| 64 | if ((fd = open(NAMEDPIPE_NAME, O_RDWR)) <= 0) { |
| 65 | perror("openfile"); |
| 66 | return 1; |
| 67 | } |
| 68 | |
| 69 | kill(pnum, SIGUSR1); |
| 70 | |
| 71 | #endif |
| 72 | cout << "Recieved messages:" << endl; |
| 73 | #ifdef _MSC_VER |
| 74 | while (true) { |
| 75 | WaitForSingleObject(hEvent, INFINITE); |
| 76 | Recieve_message(); |
| 77 | } |
| 78 | #endif |
| 79 | |
| 80 | while (true) { |
| 81 | sleep(1); |
| 82 | } |
| 83 | return 0; |
| 84 | } |
| 85 | |
| 86 | #ifdef _MSC_VER |
| 87 | |
| 88 | void Recieve_message() { |
| 89 | if (ReadFile(hNamedPipe, buffer, BUF_SIZE, &cbRead, NULL)) { |
| 90 | |
| 91 | cout << buffer << endl; |
| 92 | } |
| 93 | else { |
| 94 | DisconnectNamedPipe(hNamedPipe); |
| 95 | CloseHandle(hNamedPipe); |
| 96 | exit(0); |
| 97 | } |
| 98 | } |
| 99 | #else |
| 100 | |
| 101 | void Recieve_message() { |
| 102 | |
| 103 | memset(readbuffer, '\0', BUF_SIZE); |
| 104 | memset(buffer, '\0', BUF_SIZE); |
| 105 | read(fd, readbuffer, BUF_SIZE - 1); |
| 106 | cout << readbuffer << endl; |
| 107 | } |
| 108 | |
| 109 | #endif |