0

I'm trying to use the following program to test IPC between threads/processes under Minix. However, this code gives bizarre results - a fair number of errnos, but strangest of all, the "Creating socket was ok.."/"Binding was ok.." message appears multiple times even though it is outside of the FOR loop! That suggests that somewhere there's a buffer overflow that's arc attacking the program but I can't see where it could be. Can anyone help?

#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <time.h>
#include <mqueue.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <errno.h>

int errchk(int result, const char *action) {
    if (result == -1) {
        printf("Errno %i in %s.\n", errno, action);
    } else {
        printf("%s was ok.\n", action);
    } 
    return result;
}


int main() {
  int processes = 10;
  pid_t pids[processes];

  int threads = 0;
  int mainSock = errchk(socket(PF_UNIX, SOCK_STREAM, 0),"Creating socket");
  struct sockaddr_un sock_address;
  memset(&sock_address, 0, sizeof(sock_address));
  sock_address.sun_family = PF_UNIX;
  strcpy(sock_address.sun_path, "/chatsock");
  errchk(bind(mainSock, (struct sockaddr *)&sock_address, sizeof(sock_address)),"Binding");
  errchk(listen(mainSock, 2),"Listening");

  for (int x=0; x<processes; x++) {
    pid_t cpid = fork();
    if (cpid == 0) { // We are the subprocess
       int test = errchk(socket(PF_UNIX, SOCK_STREAM, 0),"Creating outgoing socket");
       errchk(connect(test, (struct sockaddr *)&sock_address, sizeof(sock_address)),"Connecting outgoing socket");
       pid_t myRealPid = getpid();
       int ack = 0;
       errchk(send(test, &myRealPid, sizeof(pid_t), 0),"Sending");
       exit(0);
    } else { // We are the main process
       pids[x] = cpid;
       struct sockaddr_un incoming_address;
       memset(&incoming_address, 0, sizeof(incoming_address));
       socklen_t incoming_address_length = sizeof(incoming_address);
       int incoming_socket = accept(mainSock, (struct sockaddr *)&incoming_address, &incoming_address_length);
       if (incoming_socket == -1) {
           printf("Error accepting connection %i.",errno);
       }
       pid_t got = -2;
       int ack = 2;
       int err = recv(incoming_socket, &got, sizeof(got), 0);
       //send(incoming_socket, &ack, sizeof(ack), 0);
       printf("Thread sent me %i at code %i.", got, err);
       close(incoming_socket);

    }
    close(mainSock);
  }


}
Mark Green
  • 1,310
  • 12
  • 19

0 Answers0