Exemplo n.º 1
0
int main(int argc, char *argv[])
{
	pid_t pid;
	TELL_WAIT();
	pid = Fork();
	if (pid == 0)
	{	
		while ( n < 1000)
		{
			WAIT_PARENT();
			printf(" c%d ", n);
			n += 2;
			TELL_PARENT(getppid());
			//sleep(1);
		}
		
	}
	else if(pid > 0)
	{
		while (n < 1000)
		{
			
			printf(" p%d ", n);
			n += 2;
			TELL_CHILD(pid);
		//	sleep(1);
			WAIT_CHILD();
			
		}
		
	}
	printf("Hello, world\n");
	
	return 0;
}
Exemplo n.º 2
0
int main(void) {
	pid_t	pid, mypid;

	if((pid = fork()) < 0)
		err_sys("fork error");
	else if(pid > 0) {	// parent
		mypid = getpid();
		TELL_WAIT();

		printf("%d: WAIT_CHILD()\n", mypid);
		WAIT_CHILD();
		printf("%d: wake up\n", mypid);

		sleep(2);
		printf("%d: TELL_CHILD()\n", mypid);
		TELL_CHILD(pid);
	} else {			// child
		mypid = getpid();
		TELL_WAIT();

		sleep(2);
		printf("%d: TELL_PARENT()\n", mypid);
		TELL_PARENT(getppid());

		printf("%d: WAIT_PARENT()\n", mypid);
		WAIT_PARENT();

		printf("%d: wake up\n", mypid);
	}

	return 0;
}
Exemplo n.º 3
0
/* gcc apue.h apue_err.c figure-14.5.c figure-10.24.c figure-14.7.c */
int
main(void)
{
    int     fd;
    pid_t   pid;

    /*
     * Create a file and write two bytes to it.
     */
    if ((fd = creat("templock", FILE_MODE)) < 0)
        err_sys("creat error");
    if (write(fd, "ab", 2) != 2)
        err_sys("write error");

    TELL_WAIT();        /* figure-10.24.c */
    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) {  /* child */
        lockabyte("child", fd, 0);
        TELL_PARENT(getppid());
        WAIT_PARENT();
        lockabyte("child", fd, 1);
    } else {                /* parent */ 
        lockabyte("parent", fd, 1);
        TELL_CHILD(pid);
        WAIT_CHILD();
        lockabyte("parent", fd, 0);
    }
    exit(0);
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
	int		fd;
	pid_t	pid;

	/*Create a file and write two bytes to it*/
	fd = Open("templock", O_RDWR | O_CREAT | O_TRUNC, FILE_MODE) ;

	if(write(fd, "ab", 2) != 2)
		err_sys("write error");

	TELL_WAIT();
	pid = Fork();

	if(pid == 0)
	{
		lockabyte("child", fd, 0);
		TELL_PARENT(getppid());
		WAIT_PARENT();
		lockabyte("child", fd, 1);
	}else 
	{
		lockabyte("parent", fd, 1);
		TELL_CHILD(pid);
		WAIT_CHILD();
		lockabyte("parent", fd, 0);
	}
	return 0;
}
Exemplo n.º 5
0
int main (void)
{
	pid_t	pid = 0, ppid = 0, childpid = 0;
	int		i = 0;

	init ();

	if ((pid = fork ()) < 0) {
		err_sys ("fork error");
	} else if (pid == 0) { /* child block */
		pid = getpid ();
		ppid = getppid ();
		for (i = 0; i < 100; i ++) {
			WAIT_PARENT ();
			increment (pid);
			TELL_PARENT (ppid);
		}
	} else { /* parent block */
		childpid = pid;
		pid = getpid ();
		for (i = 0; i < 100; i ++) {
			increment (pid);
			TELL_CHILD (childpid);
			WAIT_CHILD ();
		}
	}
	exit (0);
}
Exemplo n.º 6
0
int main(void)
{
    int fd;
    pid_t pid;

    if ((fd = creat("templock", FILE_MODE)) < 0)
        err_sys("creat error");

    if (write(fd, "ab", 2) != 2)
        err_sys("write error");

    TELL_WAIT();

    if ((pid = fork()) < 0){
        err_sys("fork error");
    }else if(pid == 0){/*child*/
        lockabyte("child", fd, 0);

        TELL_PARENT(getppid());
        WAIT_PARENT();

        lockabyte("child", fd, 1);
    }else{
        lockabyte("parent", fd, 1);
        TELL_CHILD(pid);
        WAIT_CHILD();
        lockabyte("parent", fd, 0);
    }

    exit(0);
}
Exemplo n.º 7
0
int main(int argc, char* argv[])
{
	int fd;
	pid_t pid;

	if((fd = creat("templock", FILEMODE)) < 0)
		printf("creat error");
	if(write(fd, "ab", 2) != 2)
		printf("write error");

	TELL_WAIT();
	if((pid = fork()) < 0)
		printf("fork error");
	else if(pid == 0)
	{
		lockabyte("child:", fd, 0);
		TELL_PARENT(getpid());
		WAIT_PARENT();
		lockabyte("child:", fd, 1);
	}
	else
	{
		lockabyte("parent:", fd, 1);
		TELL_CHILD(pid);
		WAIT_CHILD();
		lockabyte("parent:", fd, 0);
	}
	exit(0);
}
Exemplo n.º 8
0
int
main(int argc, char *argv[])
{
	int					fd;
	pid_t				pid, cpid;

	if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0)
		err_sys("open error");
	if (write(fd, "abcdef", 6) != 6)
		err_sys("write error");

	if ((pid = fork()) < 0) {
		err_sys("fork error");
	} else if (pid > 0) {
		WAIT_CHILD();
		if (write_lock(fd, 0, SEEK_SET, 1) < 0)
			err_sys("write_lock error");
		printf("gain write lock\n");
	} else {
		if (read_lock(fd, 0, SEEK_SET, 1) < 0)
			err_sys("read_lock error");
		printf("gain read lock 1\n");
		TELL_PARENT(getppid());
		if ((cpid = fork()) < 0) {
			err_sys("fork error");
		} else if (cpid > 0) {
			if (read_lock(fd, 0, SEEK_SET, 1) < 0)
				err_sys("read_lock error");
			printf("gain read lock 2\n");
		}
	}
	return 0;
}
Exemplo n.º 9
0
/* increment counter in shared memory segment; mmap /dev/zero version */ 
int main(void)
{
	int fd, i, counter;
	pid_t pid;
	void *area;

	if ((fd = open("/dev/zero", O_RDWR)) < 0)
		err_sys("open error");
	if ((area = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
			 fd, 0)) == MAP_FAILED)
		err_sys("mmap error");
	close(fd);		/* can close /dev/zero now that it is mapped */

	TELL_WAIT();

	if ((pid = Fork()) > 0) { /* parent */
		for (i = 0; i < NLOOPS; i += 2) {
			if ((counter = update((long *)area)) != i)
				err_quit("parent: expected %d, got %d", i, counter);
			TELL_CHILD(pid);
			WAIT_CHILD();
		}
	} else {		/* child */
		for (i = 1; i < NLOOPS + 1; i += 2) {
			WAIT_PARENT();
			if ((counter = update((long *)area)) != i)
				err_quit("child: expected %d, got %d", i, counter);
			TELL_PARENT();
		}
	}
	exit(0);
}
Exemplo n.º 10
0
Arquivo: a.c Projeto: klion26/APUE
int main(void)
{
    pid_t pid;
    FILE *fp;
    int fd;
    int i = 0;
    char *child = "in child\n";
    char *parent = "in parent\n";

    if ((fp = fopen("tmp", "a")) == NULL) {
        perror("fopen error");
        exit(1);
    }

    fd = fileno(fp);
    /* if (write(fd, pi, 1) != 1) { */
    /*     perror("write error"); */
    /*     exit(1); */
    /* } */
    fprintf(fp, "%d\n", i);
    fflush(fp);

    TELL_WAIT();
    if ((pid = fork()) < 0) { /* pid = fork()要用括号括起来 */
        perror("fork error");
        exit(1);
    } else if (pid == 0) {
        while (i < 100) {
            WAIT_PARENT();
            /* if (write(fd, pi, 1) != 1) { */
            /*     perror("write error"); */
            /*     exit(1); */
            /* } */
            i += 2;
            fprintf(fp, "%d\t", i);
            fflush(fp);

            write(fd, child, strlen(child));   
            TELL_PARENT(getppid());
        }
    } else {
        i++;
        while (i < 100) {
            /* if (write(fd, pi, 1) != 1) { */
            /*     perror("write error"); */
            /*     exit(1); */
            /* } */
            
            fprintf(fp, "%d\t", i);
            fflush(fp);
            i += 2;
            write(fd, parent, strlen(parent));
            TELL_CHILD(pid);
            WAIT_CHILD();
        }
    }

    return 0;
}
int main(int argc, char** argv) {

  int n;
  int fd[2];
  pid_t pid;
  int MAXLINE = 1024;
  char *line = malloc(MAXLINE * sizeof(char));

  INIT();

  if(pipe(fd) < 0){
    perror("pipe error\n");
    exit(1);
  }

  if((pid = fork()) < 0){
    perror("fork error\n");
    exit(1);
  }
  else if(pid > 0){/* parent */
    close(fd[0]);
    printf("child pid = %d\n", pid);
    for(;;){
      printf("parent > ");
      gets(line);
      write(fd[1], line, strlen(line) + 1);

      TELL_CHILD(pid);
      WAIT_FOR_CHILD();

      if(strcmp(line, "STOP") == 0)
        break;
    }
  }
  else{/* child process */
    close(fd[1]);
    for(;;){
      WAIT_FOR_PARENT();
      n = read(fd[0], line, MAXLINE);
      printf("child: %s\n", line);
      TELL_PARENT(getppid());

      if(strcmp(line, "STOP") == 0)
        break;
    }
  }

  return 0;
}
Exemplo n.º 12
0
int main(int argc,char *argv[]){
    pid_t pid;
    //set up for TELL** and WAIT**
    TELL_WAIT();
    if((pid=fork())<0){
        perror("fork error:");
        return -1;
    }else if(pid>0){
        WAIT_CHILD();
        charatatime("output from parent\n");
    }else{
        charatatime("output from child\n");
        TELL_PARENT(pid);
    }
    return 0;
}
int main()
{
    int fd = open(path, O_CREAT|O_TRUNC|O_RDWR, 0644);
    write(fd, "0", 1);
    char inbuf[20];
    char outbuf[20];
    int num;
    TELL_WAIT();
    pid_t pid;
    pid = fork();
    if(pid<0) {
        perror("fork error");
        return 1;
    } else if(pid == 0) { //child
        for(int i=0;i<10;++i) {
            lseek(fd, 0, SEEK_SET);
            ssize_t len = read(fd, inbuf, 20);
            if(len<0) break;
            inbuf[len] = 0;
            fprintf(stderr, "CHILD read %s\n",inbuf);//debug
            sscanf(inbuf,"%d",&num);
            ++num;
            lseek(fd, 0, SEEK_SET);
            sprintf(outbuf, "%d", num);
            write(fd, outbuf, strlen(outbuf));
            fprintf(stderr, "CHILD write %s\n",outbuf);//debug
            TELL_PARENT(getppid());
            WAIT_PARENT();
        }
    } else { //parent
        for(int i=0;i<10;++i) {
            WAIT_CHILD();
            lseek(fd, 0, SEEK_SET);
            ssize_t len = read(fd, inbuf, 20);
            if(len<0) break;
            inbuf[len] = 0;
            fprintf(stderr, "PARENT read %s\n",inbuf);//debug
            sscanf(inbuf,"%d",&num);
            ++num;
            lseek(fd, 0, SEEK_SET);
            sprintf(outbuf, "%d", num);
            write(fd, outbuf, strlen(outbuf));
            fprintf(stderr, "PARENT write %s\n",outbuf);//debug
            TELL_CHILD(pid);
        }
    }
}
Exemplo n.º 14
0
int main(int argc,char *argv[])
{
	pid_t pid;
	TELL_WAIT();

	if ((pid = fork()) < 0){
		perror("fork");
	}else if (pid == 0){
		TELL_PARENT(getppid());
		WAIT_PARENT();
		chara("output from child\n");
	}else{
		chara("output from parent\n");
		TELL_CHILD(pid);
	}
	exit(0);
}
Exemplo n.º 15
0
int main(void)
{
    pid_t pid;

    TELL_WAIT();

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) {
        charactatime("output from child\n");
        TELL_PARENT(getppid());      /* child goes first  */
    } else {
        WAIT_CHILD();
        charactatime("output from parent\n");
    }
    exit(0);
}
Exemplo n.º 16
0
int main(int argc, char const *argv[])
{
    pid_t pid;

    TELL_WAIT();

    if ((pid = fork()) < 0) {
        fprintf(stderr, "fork error\n");
        exit(1);
    } else if (pid == 0) {
        charatatime("output from child\n");
        TELL_PARENT(getppid());
    } else {
        WAIT_CHILD();        /* child goes first */
        charatatime("output from parent\n");
    }
    return 0;
}
Exemplo n.º 17
0
int main()
{
	int fid;
	pid_t pid;
	if((fid = open("number.txt", O_WRONLY|O_CREAT|O_TRUNC))<0)
		err_sys("create file error...\n");
	
	sprintf(str,"%d",number);
	write(fid,str,strlen(str));
	close(fid);
	
	TELL_WAIT();
	
	if((pid = fork())<0)
		err_sys("fork error");
	else if(pid==0)
	{
		while((getNumber("number.txt")+1)<1000)
		{
			WAIT_PARENT();
			number  = getNumber("number.txt");
			setNumber("number.txt",number+1);
			printf("Pid = %d,Number = %d\n",getpid(),number+1);
			TELL_PARENT(getppid());
		}
	}
	else
	{
		while((getNumber("number.txt")+1)<1000)
		{
			number  = getNumber("number.txt");
			setNumber("number.txt",number+1);
			printf("Pid = %d,Number = %d\n",getpid(),number+1);
			TELL_CHILD(pid);
			WAIT_CHILD();
		}
		
		
	}
	
	
	close(fid);
	return 0;
}
Exemplo n.º 18
0
int main(void) {
	pid_t	pid;

	TELL_WAIT();

	if((pid = fork()) < 0)
		err_sys("fork error");
	else if (pid == 0) {
		WAIT_PARENT();		/* parent goes first */
		charactatime("output from child\n");
		TELL_PARENT(getppid());
	}
	else {
		charactatime("output from parent\n");
		TELL_CHILD(pid);
		WAIT_CHILD();
	}

	return 0;
}
Exemplo n.º 19
0
/* child goes first program*/
int main()
{
	pid_t pid;
	
	TELL_WAIT();
	
	pid = fork();
	if(pid < 0) {
		printf("fork error\n");
	}
	else if(pid == 0) {
		do_task("child task\n");
		TELL_PARENT(getppid());
	}
	else {
		WAIT_CHILD();
		do_task("parent task\n");
	}
	
	return 0;
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{
	char line[MAXLINE];
	int n;
	pid_t pid;
	int fd;

	if (argc != 2)
		err_sys("usage: a.out <pathname>");
	if ((fd = open(argv[1], O_RDWR)) < 0)
		err_sys("open %s file failed", argv[1]);

	memset(line, '\0', MAXLINE);
	TELL_WAIT();
	pid = fork();
	switch (pid) {
		case -1://error
			err_sys("fork error");
		case 0://child
			WAIT_PARENT();
			lseek(fd, SEEK_SET, 0);
			if ((n = read(fd, line, MAXLINE)) < 0)
				err_sys("read error form %s", argv[1]);
			printf("read %d bytes:", n);
			fflush(stdout);
			write(STDOUT_FILENO, line, n);
			TELL_PARENT(getppid());
			break;
		default://parent
			sleep(2);
			n = write(fd, "hello child\n", 13);
			printf("write %d bytes\n", n);
			fflush(stdout);
			TELL_CHILD(pid);
			WAIT_CHILD();
			break;
	}
	close(fd);
	exit(0);
}
Exemplo n.º 21
0
int test_record_lock()
{
	int ret;
	int fd;
	pid_t pid;
	char *name;

	name = tmpnam(NULL);
	if((fd = creat(name, FILE_MODE)) < 0) {
		err_sys("create");
	}

	if (write(fd, "ab", 2) != 2)
		err_sys("write");

	TELL_WAIT();
	if ((pid = fork()) < 0)
		err_sys("fork");
	else if (pid == 0) {
		lockbyte("child", fd, 0);
		TELL_PARENT(getpid());
		WAIT_PARENT();
		lockbyte("child", fd, 1);
		sleep(2);
		exit(0);
	} else {
		lockbyte("parent", fd, 1);
		TELL_CHILD(getpid());
		WAIT_CHILD();
		lockbyte("parent", fd, 0);

		close(fd);
		sleep(1);
		unlink(name);
	}

	return 0;
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
{
    int fd;
    pid_t pid;
    void *addr = NULL;

    fd = open("/dev/zero", O_RDWR);
    if (fd < 0)
    {
        perror("open failure: ");
        return EXIT_FAILURE;
    }
    
    addr = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, fd, 0);
    if (addr == NULL)
    {
        perror("mmap failure: ");
        return EXIT_FAILURE;
    }

    close(fd); // mmap success and close fd

    TELL_WAIT();

    if ((pid = fork()) < 0)
    {
        perror("fork failure: ");
        return EXIT_FAILURE;
    }
    else if (pid == 0)
    {
        int i = 0;
        pid = getpid();

        for (i = 0; i < 1000; i+=2)
        {
            if (update((int *)addr) != i)
            {
                fprintf(stderr, "child process sync failure, i = %d\n", i);
                return EXIT_FAILURE;
            }

            printf("child start ##############\n");
            TELL_PARENT(pid);
            WAIT_PARENT();
        }
    }
    else
    {
        int i = 0;
        pid = getpid();

        for (i = 1; i < 1000; i+=2)
        {
            WAIT_CHILD();
            printf("parent start   @@@@@@@@@@@@@@\n");

            if (update((int *)addr) != i)
            {
                fprintf(stderr, "parent process sync failure, i = %d\n", i);
                return EXIT_FAILURE;
            }

            TELL_CHILD(pid);
        }
    }

    munmap(addr, sizeof(int));

    return EXIT_SUCCESS;
}
Exemplo n.º 23
0
int servopen(char* host, char* port)
{
    int fd, newfd, i, on, pid;
    const char* protocol;
    struct in_addr inaddr;
    struct servent* sp;

    protocol = udp ? "udp" : "tcp";

    /* Initialize the socket address structure */
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;

    /* Caller normally wildcards the local Internet address, meaning
           a connection will be accepted on any connected interface.
           We only allow an IP address for the "host", not a name. */
    if (host == NULL)
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* wildcard */
    else {
        if (inet_aton(host, &inaddr) == 0)
            err_quit("invalid host name for server: %s", host);
        servaddr.sin_addr = inaddr;
    }

    /* See if "port" is a service name or number */
    if ((i = atoi(port)) == 0) {
        if ((sp = getservbyname(port, protocol)) == NULL)
            err_ret("getservbyname() error for: %s/%s", port, protocol);

        servaddr.sin_port = sp->s_port;
    } else
        servaddr.sin_port = htons(i);

    if ((fd = socket(AF_INET, udp ? SOCK_DGRAM : SOCK_STREAM, 0)) < 0)
        err_sys("socket() error");

    if (reuseaddr) {
        on = 1;
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
            err_sys("setsockopt of SO_REUSEADDR error");
    }

#ifdef SO_REUSEPORT
    if (reuseport) {
        on = 1;
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) < 0)
            err_sys("setsockopt of SO_REUSEPORT error");
    }
#endif

    /* Bind our well-known port so the client can connect to us. */
    if (bind(fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
        err_sys("can't bind local address");

    join_mcast(fd, &servaddr);

    if (udp) {
        buffers(fd);

        if (foreignip[0] != 0) { /* connect to foreignip/port# */
            bzero(&cliaddr, sizeof(cliaddr));
            if (inet_aton(foreignip, &cliaddr.sin_addr) == 0)
                err_quit("invalid IP address: %s", foreignip);
            cliaddr.sin_family = AF_INET;
            cliaddr.sin_port = htons(foreignport);
            /* connect() for datagram socket doesn't appear to allow
                   wildcarding of either IP address or port number */

            if (connect(fd, (struct sockaddr*)&cliaddr, sizeof(cliaddr)) < 0)
                err_sys("connect() error");
        }

        sockopts(fd, 1);

        return (fd); /* nothing else to do */
    }

    buffers(fd);     /* may set receive buffer size; must do here to get
                               correct window advertised on SYN */
    sockopts(fd, 0); /* only set some socket options for fd */

    listen(fd, listenq);

    if (pauselisten)
        sleep_us(pauselisten * 1000); /* lets connection queue build up */

    if (dofork) TELL_WAIT(); /* initialize synchronization primitives */

    for (;;) {
        i = sizeof(cliaddr);
        if ((newfd = accept(fd, (struct sockaddr*)&cliaddr, &i)) < 0)
            err_sys("accept() error");

        if (dofork) {
            if ((pid = fork()) < 0) err_sys("fork error");

            if (pid > 0) {
                close(newfd); /* parent closes connected socket */
                WAIT_CHILD(); /* wait for child to output to terminal */
                continue;     /* and back to for(;;) for another accept() */
            } else {
                close(fd); /* child closes listening socket */
            }
        }

        /* child (or iterative server) continues here */
        if (verbose) {
            /* Call getsockname() to find local address bound to socket:
                   local internet address is now determined (if multihomed). */
            i = sizeof(servaddr);
            if (getsockname(newfd, (struct sockaddr*)&servaddr, &i) < 0)
                err_sys("getsockname() error");

            /* Can't do one fprintf() since inet_ntoa() stores
                           the result in a static location. */
            fprintf(stderr, "connection on %s.%d ",
                    INET_NTOA(servaddr.sin_addr), ntohs(servaddr.sin_port));
            fprintf(stderr, "from %s.%d\n", INET_NTOA(cliaddr.sin_addr),
                    ntohs(cliaddr.sin_port));
        }

        buffers(newfd);     /* setsockopt() again, in case it didn't propagate
                                   from listening socket to connected socket */
        sockopts(newfd, 1); /* can set all socket options for this socket */

        if (dofork)
            TELL_PARENT(getppid()); /* tell parent we're done with terminal */

        return (newfd);
    }
}
Exemplo n.º 24
0
/** 
 * main()
 * 
 * This program comprises two processes.  First, the "brain" which
 * communicates with a supervisor-client.  The brain receives
 * high-level control commands from the supervisor-client and then
 * conveys any resulting sensor data back.  The second process is the
 * "nerves"; this process translates high-level commands into
 * low-level iRobot SCI commands, executes them on the iRobot, and
 * then obtains any resulting sensor data.
 * 
 */
int main(int argc, char* argv[])
{

  /* Create a message queue using O_CREAT so that if the queue doesn't
   * already exist, it will be created.  When using mq_open with
   * O_CREAT, one must supply four arguments.  The first "name"
   * argument must begin with a slash.  The third "mode" argument is
   * derived from the symbolic constants is <sys/stat.h>.
   */
   mqd_t mqd_cmd = mq_open("/q_cmd", 
		    O_RDWR | O_CREAT , 
		    S_IRWXU | S_IRWXG | S_IRWXO, 
		    NULL);

   mqd_t mqd_sns = mq_open("/q_sns", 
		    O_RDWR | O_CREAT, 
		    S_IRWXU | S_IRWXG | S_IRWXO, 
		    NULL);
 
  printf("The message queue id is: %d\n", mqd_cmd);

  /* Determine the size of messages for this message queue
   */
  struct mq_attr a;
  mq_getattr(mqd_cmd,&a);  

  printf("The default message size is: %d\n", a.mq_msgsize);
   
   if( mqd_cmd == -1)
    {
      perror("mq_open():");
      return -1;
    }


   if( mqd_sns == -1)
    {
      perror("mq_open():");
      return -1;
    }

  

  int check = 0;
  char addresses[3][13];
  if ((check = checkArgName(argc, argv, addresses)) == -1)
    {
      printf("Not correct name entered. Exiting.\n");
      exit(0);
    }
  int i, counter, serverID, clientSock, numBytes;
  pid_t pid, pid2;

  // Arrays to hold most recent command sent by the
  // supervisor-client and the most recent command sent to the iRobot.
  char commandFromSupervisor[MAXDATASIZE] = {'\0'};
  char commandToRobot[MAXDATASIZE] = {'\0'};

  // An array to hold sensor data sent to the supervisor-client and
  // obtained from the iRobot.
  char sensDataToSupervisor[MAXDATASIZE] = {'\0'};
  char sensDataFromRobot[MAXDATASIZE] = {'\0'};
  char emptyDataToSupervisor[MAXDATASIZE] = "0000000000 ";
  char rawTimeString[12] = {'\0'};

  // An array to hold the timestamp.
  char currTime[100];


  // Create pipe to communicate between parent and child
  int fd[2];
  if(pipe(fd) < 0)
    perror("pipe error");

  //------------------------------------------------------------------------
  // Added Code to implement client
  //------------------------------------------------------------------------
  int sockfd, numbytes;  
  //buffer to store sensor information
  char sensorBuf[MAXDATASIZE];
  char msgBuf[MAXDATASIZE];
  struct addrinfo hints, *servinfo, *p;
  int rv;
  char s[INET6_ADDRSTRLEN];
  //array to hold the command sent
  char cmd[1];
  //initialize the input to NULL char
  char input = '\0';
  //------------------------------------------------------------------------
  // End of added section
  //------------------------------------------------------------------------ 

  // Create a socket-based server
  if((serverID = createServer()) == -1)
    {
      perror("createServer()");
      return -1;
    }

  printf("brainstem: waiting for connections...\n");


  // Establish a client-connection for the socket-based server
  if((clientSock = establishConnection(serverID)) == -1)
    {
      perror("establishConnection(serverID)");
      return -1;
    }
  

  // Set up signal-based communication between the child 
  // (brain) and parent (nervous system) to avoid possible
  // race conditions.
  TELL_WAIT();



  // Fork a child process.  This process will handle the "brain"
  // activities: communicating sensor data to the client
  // and receiving control commands from the client.
  if(( pid = fork()) < 0)
    {
      perror("fork error");

    }



  //------------------------------------------------------------------------
  // Code for parent (nerves)
  //------------------------------------------------------------------------
  else if (pid > 0)
    {

      // Close the client socket since this parent won't be using it.
      close(clientSock);

      //TELL_CHILD(pid);

      // Open the serial port to the robot.  If this is unsuccessful,
      // there is no point in continuing.
      if(openPort() == 0)
	{
	  printf("Port failed to open \n");
	  exit(-1);
	}

      // Initialize the robot, prepare it to receive commands.  Wait
      // for a second to give this some time to take effect.
      initialize();
      sleep(1);


#ifdef TARGET_WEBBY
      // Initialize the compass device.
      initializeCompass();

      // This is temporary until turn() works.
      // Turn Left 10 degrees
      turn(TURN_LEFT, 10);
#endif 


      // Turn on the LED to indicate the robot is ready and listening.
      // It's a nice sanity check.
      setLED(RED, PLAY_ON, ADVANCE_ON);

      //------------------------------------------------------------------------
      // Added Code to implement client
      //------------------------------------------------------------------------
      if(check == 1)
	{
#ifdef DEBUG
	  printf("%s %d \n", __FILE__, __LINE__);
#endif
      
	  memset(&hints, 0, sizeof hints);
	  hints.ai_family = AF_UNSPEC;
	  hints.ai_socktype = SOCK_STREAM;
    
	  if ((rv = getaddrinfo(addresses[1], PORT, &hints, &servinfo)) != 0) 
	    {
	      fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
	      return 1;
	    }
    
	  // loop through all the results and connect to the first we can
	  for(p = servinfo; p != NULL; p = p->ai_next) 
	    {
	      if ((sockfd = socket(p->ai_family, p->ai_socktype,
				   p->ai_protocol)) == -1) {
		perror("client: socket");
		continue;
	      }
      
	      if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
		close(sockfd);
		perror("client: connect");
		continue;
	      }
      
	      break;
	    }
    
	  if (p == NULL) 
	    {
	      fprintf(stderr, "client: failed to connect\n");
	      return 2;
	    }
    
	  inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
		    s, sizeof s);
	  printf("client: connecting to %s\n", s);
    
	  freeaddrinfo(servinfo); // all done with this structure
    
	  //if the client does not recieve anything from server then exit
	  if ((numbytes = recv(sockfd, msgBuf, MAXDATASIZE-1, 0)) == -1) 
	    {
	      perror("recv");
	      exit(1);
	    }
	}

      //------------------------------------------------------------------------
      // End of added section
      //------------------------------------------------------------------------

      while(commandToRobot[0] != ssQuit)
	{
	  commandToRobot[0] = 'z';
	  // Wait until a valid command is received.
	  while(commandToRobot[0] == 'z')
	    {
          commandToRobot[0] = readFromMessageQueueAndExecute(mqd_cmd);
	      
	    }

	  printf("commandToRobot: %d\n", commandToRobot[0]);
	  //------------------------------------------------------------------------
	  // Added Code to implement client
	  //------------------------------------------------------------------------
	  if(check == 1)
	    {
	      if(send(sockfd, &commandToRobot[0], 1, 0) == -1)
		perror("send");
	      printf("      the command code sent was: %d\n", commandToRobot[0]);
	    }
	  //------------------------------------------------------------------------
	  // End of added section
	  //------------------------------------------------------------------------

	  receiveGroupOneSensorData(sensDataFromRobot);

	  // check if any of the sensor data indicates a 
	  // sensor has been activated.  If so, react be
	  // driving backwards briefly and then stopping.
	  
	  int sensData = 0;

	  // Check sensor data first to stop ramming into wall.
	  sensData = checkSensorData(sensDataFromRobot);

#ifdef DEBUG
	  printf("%s %d \n", __FILE__, __LINE__);
#endif
	  // Wait until child has sent previous sensor data.
	  //WAIT_CHILD();

#ifdef DEBUG

	  printf("%s %d \n", __FILE__, __LINE__);
	  printf("%d \n", sensData);
#endif

	  if(sensData)
	    {
#ifdef DEBUG
	      printf("%s %d \n", __FILE__, __LINE__);	     	      
#endif
	      // Drive backwards and then stop.
	      driveBackwardsUntil(EIGHTH_SECOND, MED);
	      STOP_MACRO;	      

	      // Convey sensorData back to the child.
	      writeSensorDataToMessageQueue(sensDataFromRobot, mqd_sns, getTime(), getRawTime());

	    }  
	  // Done writing sensor data, tell child to proceed reading sensor data.
	  TELL_CHILD(pid);
	  
	  // Reset the array; fill it again in the next loop.
	  for(i = 0; i <= 6; i++)
	    {
	      sensDataFromRobot[i]= FALSE;
	    }
	}


      if (closePort() == -1)
	{
	  perror("Port failed to close \n");
	  exit(-1);
	}
      send(sockfd, &input, 1, 0);
      close(sockfd);
      kill(0, SIGTERM);
      mq_close(mqd_cmd);

      exit(0);
    }

  //------------------------------------------------------------------------
  // Code for child (brain)
  //------------------------------------------------------------------------
  else
    {
      // Child process doesn't need the listener.
      close(serverID);

      // Initially tell the parent to proceed and write sensor data.
      //TELL_PARENT(getppid());

      // Send the client the initial connection message.
      if(send(clientSock, MSG, sizeof(MSG), 0) == -1)
	perror("send");

      // At the request of the supervisor implementation team, The
      // brain follows a strict alternation of 'receive control
      // command' then 'send sensor data'.  If the control command
      // sent by the supervisor-client is 'turn left' and the iRobot
      // happens to bump into something, then the subsequent message
      // to the supervisor-client will indicate which bumper was activated.  
      // Similarly, if the control command sent by the supervisor is
      // 'turn left' and the iRobot experiences no sensory input, the
      // subsequent message to the supervisor will indicate that no sensors
      // were activated.

      // As long as the quit command 'q' has not been sent by the
      // supervisor-client, receive a control command and send the
      // subsequent sensor data.
      while(commandFromSupervisor[0] != ssQuit)
	{
	  // Wait to receive command from supervisor-client; read the command
	  // into cmdBuf.
	  if ((numBytes = recv(clientSock, commandFromSupervisor, MAXDATASIZE-1, 0)) == -1)
	    {
	      perror("recv");
	      return -1;
	    }
	  // Write the read command into shared memory so that the
	  // parent (nerves) may read and execute it.
	  //writeCommandToSharedMemory(commandFromSupervisor, cmdArea,mqd_cmd);
      writeCommandToMessageQueue(commandFromSupervisor,mqd_cmd);

	  // Wait until parent has written sensor data.
	  WAIT_PARENT();

#ifdef DEBUG
	  printf("%s %d \n", __FILE__, __LINE__);
#endif

	  // If there is sensor data available, send it to the
	  // supervisor-client.
	  if(readSensorDataFromMessageQueue(sensDataToSupervisor, mqd_sns))
	    {
	      printf("\nsensDataToSupervisor: %s \n", sensDataToSupervisor);
	      if(send(clientSock, sensDataToSupervisor, strlen(sensDataToSupervisor)-1 , 0) == -1)
		perror("send");
	    }
	  
	  // Otherwise, assume no sensor was activated.  Send an empty
	  // sensor message to the supervisor-client.
	  else
	    {
	      itoa(getRawTime(), rawTimeString);
	      
	      // Construct an empty sensor data message and send it to
	      // the supervisor-client.
	      strncat(emptyDataToSupervisor, rawTimeString, MAXDATASIZE-SIZE_OF_EMPTY_DATA);
	      strncat(emptyDataToSupervisor, " ", 1);
	      strncat(emptyDataToSupervisor, getTime(), MAXDATASIZE-SIZE_OF_EMPTY_DATA);
	      printf("\nemptySensDataToSupervisor: %s \n", emptyDataToSupervisor);
	      if(send(clientSock, emptyDataToSupervisor, MAXDATASIZE-1, 0) == -1)
		perror("send");

	      emptyDataToSupervisor[SIZE_OF_EMPTY_DATA] = '\0';
	    }

	  // Done reading sensor data, allow parent to write more sensor data.
	  TELL_PARENT(getppid());
	}
	

      // All done.  Clean up the toys and go home.
      printf("Closing socket and terminating processes.\nHave a nice day!\n");
      kill(pid, SIGTERM);
      close(clientSock);
      mq_close(mqd_cmd);

      exit(0);
    }
  // Added following code to implement communication between roomba's
 
  
	  
}