sockpong.c (2160B)
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* This Source Code Form is subject to the terms of the Mozilla Public 3 * License, v. 2.0. If a copy of the MPL was not distributed with this 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 5 6 /* 7 * File: sockpong.c 8 * 9 * Description: 10 * This test runs in conjunction with the sockping test. 11 * The sockping test creates a socket pair and passes one 12 * socket to this test. Then the sockping test writes 13 * "ping" to this test and this test writes "pong" back. 14 * To run this pair of tests, just invoke sockping. 15 * 16 * Tested areas: process creation, socket pairs, file 17 * descriptor inheritance. 18 */ 19 20 #include "prerror.h" 21 #include "prio.h" 22 23 #include <stdio.h> 24 #include <string.h> 25 #include <stdlib.h> 26 27 #define NUM_ITERATIONS 10 28 29 int main(int argc, char** argv) { 30 PRFileDesc* sock; 31 PRStatus status; 32 char buf[1024]; 33 PRInt32 nBytes; 34 int idx; 35 36 sock = PR_GetInheritedFD("SOCKET"); 37 if (sock == NULL) { 38 fprintf(stderr, "PR_GetInheritedFD failed\n"); 39 exit(1); 40 } 41 status = PR_SetFDInheritable(sock, PR_FALSE); 42 if (status == PR_FAILURE) { 43 fprintf(stderr, "PR_SetFDInheritable failed\n"); 44 exit(1); 45 } 46 47 for (idx = 0; idx < NUM_ITERATIONS; idx++) { 48 memset(buf, 0, sizeof(buf)); 49 nBytes = PR_Read(sock, buf, sizeof(buf)); 50 if (nBytes == -1) { 51 fprintf(stderr, "PR_Read failed: (%d, %d)\n", PR_GetError(), 52 PR_GetOSError()); 53 exit(1); 54 } 55 printf("pong process: received \"%s\"\n", buf); 56 if (nBytes != 5) { 57 fprintf(stderr, "pong process: expected 5 bytes but got %d bytes\n", 58 nBytes); 59 exit(1); 60 } 61 if (strcmp(buf, "ping") != 0) { 62 fprintf(stderr, "pong process: expected \"ping\" but got \"%s\"\n", buf); 63 exit(1); 64 } 65 66 strcpy(buf, "pong"); 67 printf("pong process: sending \"%s\"\n", buf); 68 nBytes = PR_Write(sock, buf, 5); 69 if (nBytes == -1) { 70 fprintf(stderr, "PR_Write failed\n"); 71 exit(1); 72 } 73 } 74 75 status = PR_Close(sock); 76 if (status == PR_FAILURE) { 77 fprintf(stderr, "PR_Close failed\n"); 78 exit(1); 79 } 80 return 0; 81 }