- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <math.h>
- #include <string.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #define PI 3.1415926
- #define TIMER0 0
- #define PORT 5000 // The port which is communicate with server
- #define BACKLOG 10
- void nettran1(void* nsockfd);
- int main (void)
- {
- int sockfd,nsockfd;
- int opt;
- struct sockaddr_in addr_local;
- pthread_t threadid1;
- pthread_attr_t attr;
- struct sockaddr_in addr_remote; // New Socket file descriptor
- int sin_size; // to store struct size
- sin_size = sizeof (struct sockaddr_in);
- if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
- {
- printf ("ERROR: Cannot obtain Socket Despcritor\n");
- exit(1);
- }
-
- else
-
- {
- printf ("OK: Obtain Socket Despcritor sucessfully\n");
- }
- /* Fill the local socket address struct */
- addr_local.sin_family = AF_INET; // Protocol Family
- addr_local.sin_port = htons (PORT); // Port number
- addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
- bzero (&(addr_local.sin_zero), 8); // Flush the rest of struct
- opt = SO_REUSEADDR;
-
- setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));
-
- /* Blind a special Port */
- if (bind(sockfd, (struct sockaddr *) &addr_local, sizeof (struct sockaddr)) == -1)
- {
-
- printf ("ERROR: Cannot bind Port %d\n", PORT);
- exit(1);
- }
-
- else
-
- {
-
- printf ("OK: Bind the Port %d sucessfully\n", PORT);
-
- }
- /* Listen remote connect/calling */
- if (listen (sockfd, BACKLOG) == -1)
- {
- printf ("ERROR: Cannot listen Port %d\n", PORT);
-
- exit(1);
-
- }
-
- else
-
- {
-
- printf ("OK: Listening the Port %d sucessfully\n", PORT);
-
- }
- while(1)
- {
- perror("Is there any error?") ;
- /* Wait a connection, and obtain a new socket file despriptor for single connection */
- if ((nsockfd = accept (sockfd, (struct sockaddr *) &addr_remote,&sin_size)) != -1)
- {
- printf ("OK: Server has got connect from %s %d\n", inet_ntoa (addr_remote.sin_addr),nsockfd);
- pthread_attr_init(&attr);
- pthread_attr_setstacksize(&attr,100);
- perror("Is there any error1?") ;
- if(pthread_create(&threadid1,&attr,(void*)(nettran1),(void*)nsockfd)!=0)
- {
- perror("Error to create thread") ;
- close (nsockfd);
- continue;
- }
- /* pthread_detach(threadid1,NULL); */
- pthread_join(threadid1,NULL);
- }
-
- }
- //close (nsockfd);
- }
- void nettran1(void* nsockfd)
- {
- double value;
- char sdbuf[8];
- int num,i=0,sig=4;
- while(1)
- {
- perror("send0:");
- if(i++>90) i = 0;
- value = sin (i * PI/ 45);
- perror("send1:");
- gcvt (value, sig, sdbuf);
- perror("send:");
- printf("value=%s %d\n",sdbuf,(int)nsockfd);
- // SendMessage((HWND)hwnd,MSG_MYMESSAGE,0,0);
- if ((num = send ((int)nsockfd,&sdbuf, sizeof (sdbuf),0)) ==-1)
- {
- perror("send:");
- close ((int)nsockfd) ;
- pthread_exit(NULL);
- }
- }
- }
复制代码
代码如上,多线程函数运行后,perror检测到异常:Interrupted system call。send发动不成功。 |
|