[comp.unix.wizards] Socket datagram again.

hubert@spica.ucsb.edu (05/15/91)

Thanks to Kiartik and Oliver. I got the datagram working.

But when I tried  the following program(which could be wrong. I am a rooky.)
 I found out that if I don't add exit(0) at the end of the program. The
a.out will give me segment fault. Whay is that?



#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>

struct record
{
    int from;
    int to[10];
}

main()
{
int s1,s2,ret,fromlen;
struct sockaddr	sock1,sock2,stemp;
struct record r1,r2;

	sock1.sa_family=PF_UNIX; sock2.sa_family=PF_UNIX;
	sprintf(sock1.sa_data,"sock1"); sprintf(sock2.sa_data,"sock2");
	unlink(sock1.sa_data); unlink(sock2.sa_data);

	if ((s2=socket(PF_UNIX, SOCK_DGRAM,0)) == -1)
		perror("child socket creating error \n");

	if (bind(s2, &sock2,sizeof(sock2))==-1)
			perror("child binding eror\n");

	if ((s1=socket(PF_UNIX, SOCK_DGRAM,0)) == -1)
		perror("parent socket creating error \n");

	if (bind(s1, &sock1,sizeof(sock1))==-1)
		perror("parent binding eror\n");

	r1.from=10;
	r1.to[0]=9;

	if (sendto(s1, &r1, sizeof(struct record),0, &sock2,sizeof(sock2))==-1)
		perror("parent send error\n");

	if ( fork()==0)
	{
		printf("child birth\n");

		if (recvfrom(s2, (char *) &r2, sizeof(struct record),0,&stemp,&fromlen) == -1)
			perror("child receive error\n");
		else 
		{
			printf("child got:%d\n",r2.from);
			printf("child got:%d\n",r2.to[0]);
		}

	printf("child o.k\n");

		exit(0);
	}

	printf("parent\n");

	if (wait(&ret) ==-1)
		perror("wait error \n");

	printf("parent o.k\n");

	if (close(s1)== -1)
		perror("close fail"); 
	if (close(s2)==-1)
		perror("close s2 fail");

	exit(0);

}
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Hung-Hsien Chang ( Hubert)		E-mail: hubert@cs.ucsb.edu

P.S: Hubert is not my middle name; it is easier for American friends to call me.

hue@island.COM (Pond Scum) (05/18/91)

In article <11242@hub.ucsb.edu> hubert@spica.ucsb.edu writes:
>But when I tried  the following program(which could be wrong. I am a rooky.)
> I found out that if I don't add exit(0) at the end of the program. The
>a.out will give me segment fault. Whay is that?

Please take these questions to comp.lang.c.  This isn't the group for it.
Or better yet, try to find someone locally who can answer your questions.

>struct record
>{
>    int from;
>    int to[10];
>}
>
>main()

You've just declared main as a function that returns struct record.  Put
a semicolon after the curly brace.  You're trashing the stack which causes
the seg fault when you return from main.  By calling exit you avoid
returning from main with a trashed stack.

-Jonathan		hue@island.COM