Steven Luk wrote:
> Please I need help fixing this "segmentation fault" problem in my
> mulitithreaded echo server code.
I don't claim to be an expert at these things, but I believe I see the problem.
> -- server code --
> static void *doit(void *); /* each thread executes this function */
> void str_echo(int);
> static int *status;
>
> int
> main(int argc, char **argv)
> {
> int listenfd, rc;
> int *iptr;
> unsigned short port_num;
> int clilen;
> struct sockaddr_in cliaddr, servaddr;
>
> if(argc != 2)
> {
> printf("Usage: %s port\n", argv[0]);
> exit(1);
> }
>
> port_num = (unsigned short) atoi(argv[1]);
>
> listenfd = socket(PF_INET, SOCK_STREAM, 0);
>
> bzero(&servaddr, sizeof(servaddr));
> servaddr.sin_family = PF_INET;
> servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
> servaddr.sin_port = htons(port_num);
>
> bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
>
> listen(listenfd, 5);
>
> for ( ; ; ) {
> //len = addrlen;
> iptr = malloc(sizeof(int));
> *iptr = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
At this point, accept() has blocked until the client attempted it's
connection. The accept() call has now unblocked and processing can continue.
This gives us a synchronization point; your code crashes at some point /after/
the accept() call.
> if ((rc = pthread_create(NULL, NULL, &doit, iptr)) > 0)
I believe that this is your problem.
The manpage for pthread_create(3) says that the first argument is a pointer to
a pthread_t. You have the first argument set to the NULL pointer. This is
important because pthread_create(3) says
"RETURN VALUE
On success, the identifier of the newly created thread is
stored in the location pointed by the |thread| argument,
and a 0 is returned. On error, a non-zero error code is
returned."
It is this |thread| argument that you've set to NULL. pthread_create(3) is
trying to store the thread identifier, and you've directed it to store the
identifier at NULL. This is likely the cause of your segmentation violation;
NULL is not contained within your address space.
Fix this and try again. Let us know what the results are.
> err_quit("Error Create Thread\n");
> }
> exit(0);
> }
[rest of code snipped]
> Right now I just have the server send an "OK" message back to the client.
> But I always get the "segmentation fault" every time the client tries to
> connect.
>
> [root@linuxgw proj3]# ./tcpserv02 2033
> Segmentation fault
>
> [root@linuxgw proj3]# ./tcpcli02 127.0.0.1 2033
> OK!
> server terminated prematurely
>
> Both programs compiled w/o warnings/errors. Any ideas?
>
>
--
Lew Pitcher
Master Codewright and JOAT-in-training
Registered Linux User #112576 (
http://counter.li.org/)
Slackware - Because I know what I'm doing.