嵌入式程序教程.doc
文本预览下载声明
多线程:
#include stdio.h
#include stdlib.h
#include unistd.h
#include sys/ioctl.h
#include pthread.h
int task1(int *cnt)
{
while(*cnt 5)
{
sleep(1);
(*cnt)++;
printf(task1 cnt = %d.\n, *cnt);
}
return (*cnt);
}
int task2(int *cnt)
{
while(*cnt 5)
{
sleep(2);
(*cnt)++;
printf(task2 cnt = %d.\n, *cnt);
}
return (*cnt);
}
int main(int argc, char **argv)
{
int result;
int t1 = 0;
int t2 = 0;
int rt1, rt2;
pthread_t thread1, thread2;
/* create the first thread. */
result = pthread_create(thread1, PTHREAD_CREATE_JOINABLE, (void *)task1, (void *)t1);
if(result)
{
perror(pthread_create: task1.\n);
exit(EXIT_FAILURE);
}
/* create the second thread. */
result = pthread_create(thread2, PTHREAD_CREATE_JOINABLE, (void *)task2, (void *)t2);
if(result)
{
perror(pthread_create: task2.\n);
exit(EXIT_FAILURE);
}
pthread_join(thread1, (void *)rt1);
pthread_join(thread2, (void *)rt2);
printf(total %d times.\n, t1+t2);
printf(return value of task1: %d.\n, rt1);
printf(return value of task2: %d.\n, rt2);
exit(EXIT_SUCCESS);
}
TCP(sever):
#include stdlib.h
#include stdio.h
#include errno.h
#include string.h
#include sys/types.h
#include netinet/in.h
#include sys/wait.h
#include sys/socket.h
#define PORT 5000 // The port which is communicate with server
#define BACKLOG 10
#define LENGTH 512 // Buffer length
int main ()
{ int sockfd; // Socket file descriptor
int nsockfd; // New Socket file descriptor
int num;
int sin_size; // to store struct size
char sdbuf[LENGTH]; // Send buffer
struct sockaddr_in addr_local;
struct sockaddr_in addr_remote;
char sendstr[16]= {123456789 abcde};
/* Get the Socket file descriptor */
if( (sockfd = socket(AF_IN
显示全部