Linux下的示例程序
linux下的示例程序
#if 0
/*
* 1. 遍历目录-1
*/
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
void show_directory(char* path)
{
DIR *dir;
struct dirent*entry;
static int count=0;
int i=0;
int j=0;
if(NULL==(dir=opendir(path)))
printf("error opening dir\n");
else {
chdir(path);
// system("pwd");
count+=1;
while(entry=readdir(dir))
{
// if(strcmp(entry->d_name,".")==0||
// strcmp(entry->d_name,"..")==0)
if((entry->d_name)[0]=='.')
continue;
i=0;
j=0;
switch(entry->d_type){
case DT_DIR:
while(i++<count)
printf("+");
printf("\e[32;44m%s\e[0m\n",entry->d_name );
show_directory(entry->d_name);
break;
case DT_REG:
while(j++<count+4)
printf("-");
printf("\e[30;41m%s\e[0m\n",entry->d_name );
break;
default:
printf("%s\n",entry->d_name );
break;
}
}
count-=1;
chdir("..");
closedir(dir);
}
}
int main(int argc,char**argv)
{
if(argc<2)
{
printf("Not enough arguments!\n");
return -1;
}
show_directory(argv[1]);
return 0;
}
#endif
#if 0
/*
* 遍历目录-2
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#define MAX_PATH 1024
void dirwalk(char *dir,void(*fcn)(char*))
{
char name[MAX_PATH];
struct dirent *dp;
DIR *dfd;
if((dfd=opendir(dir))==NULL) {
fprintf(stderr,"dirwalk:can't open %s\n",dir);
return ;
}
while((dp=readdir(dfd))!=NULL){
if(strcmp(dp->d_name,".")==0||
strcmp(dp->d_name,"..")==0)
continue;
if(strlen(dir)+strlen(dp->d_name)+2>sizeof(name))
fprintf(stderr,"dirwalk:name %s/%s too long\n",dir,dp->d_name);
else{
sprintf(name,"%s/%s",dir,dp->d_name);
printf("%s\n",name);
fcn(name);
}
}
closedir(dfd);
}
int main(int argc,char**argv)
{
char *dir;
if(argc<2){
fprintf(stderr,"Usage:dirwalk <dir>\n");
return 1;
}
dir=argv[1];
dirwalk(dir,dirwalk);
}
#endif
#if 0
/*
* 遍历目录-3
*/
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir, pwd[2]=".";
if (argc != 2)
topdir=pwd;
else
topdir=argv[1];
printf("Directory scan of %s:\n",topdir);
printdir(topdir,0);
printf("------done-------\n");
return (0);
}
#endif
#if 0
/*
* 2. 利用管道进行读写
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void writer(const char *message,int count,FILE* stream)
{
for(;count>0;--count)
{
fprintf(stream,"%s\n",message);
fflush(stream);
sleep(1);
}
}
void reader(FILE*stream)
{
char buffer[1024];
while(!feof(stream)&&!ferror(stream)
&&fgets(buffer,sizeof(buffer),stream)!=NULL)
{
fputs(buffer,stdout);
}
}
int main()
{
int fds[2];
pid_t pid;
pipe(fds);
pid=fork();
if(pid==(pid_t)0){
FILE *stream;
close(fds[1]);
stream=fdopen(fds[0],"r");
reader(stream);
close(fds[0]);
}
else{
FILE *stream;
close(fds[0]);
stream=fdopen(fds[1],"w");
writer("Hello,world.",10,stream);
close(fds[1]);
}
}
#endif
#if 0
/*
* 3. 利用stat来获得系统文件的相关信息
*/
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc,char**argv)
{
struct stat buf;
mode_t mode;
char type[80];
int fd;
if(argc!=2){
puts("Usage:mstat {file}");
exit(EXIT_FAILURE);
}
if((fd=open(argv[1],O_RDONLY))<0){
perror("open");
exit(EXIT_FAILURE);
}
if((fstat(fd,&buf))<0){
perror("open");
exit(EXIT_FAILURE);
}
mode=buf.st_mode;
printf(" FILE:%s\n",argv[1]);
printf(" INODE:%ld\n",buf.st_ino);
printf(" DEVICE:%d,%d\n",major(buf.st_dev),
minor(buf.st_dev));
printf(" MODE:%#o\n",mode&~(S_IFMT));
printf(" LINKS:%d\n",buf.st_nlink);
printf(" UID:%d\n",buf.st_uid);
printf(" GID:%d\n",buf.st_gid);
if(S_ISLNK(mode))
strcpy(type,"Symbolic line");
else if(S_ISREG(mode))
strcpy(type,"Regular file");
else if(S_ISDIR(mode))
strcpy(type,"Directory");
else if(S_ISCHR(mode))
strcpy(type,"Character device");
else if(S_ISBLK(mode))
strcpy(type,"Block device");
else if(S_ISFIFO(mode))
strcpy(type,"FIFO");
else if(S_ISSOCK(mode))
strcpy(type,"Socket");
else
strcpy(type,"Unknown type");
printf(" TYPE:%s\n",type);
printf(" SIZE:%ld\n",buf.st_size);
printf("BLK SIZE:%ld\n",buf.st_blksize);
printf(" BLOCKS:%d\n",(int)buf.st_blocks);
printf("ACCESSED:%s",ctime(&buf.st_atime));
printf("MODIFIED:%s",ctime(&buf.st_mtime));
printf(" CHANGED:%s",ctime(&buf.st_ctime));
if(close(fd)<0){
perror("close");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
#endif
#if 0
/*
* 4. 利用socket进行通信
* server端程序:
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
char* read_tempfile(const char *filename){
int fd;
size_t length;
char *buffer;
fd=open(filename,O_RDONLY);
lseek(fd,0,SEEK_SET);
read(fd,&length,sizeof(size_t));
buffer=malloc(length);
read(fd,buffer,length);
close(fd);
return buffer;
}
int main()
{
char*buffer;
char filename[200];
int length;
int fd;
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 9734;
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *) &server_address, server_len);
listen(server_sockfd, 5);
while (1) {
printf("Server is waiting ....\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *) &client_address,
(socklen_t *__restrict) &client_len);
read(client_sockfd, &length, sizeof(length));
read(client_sockfd,filename,length);
buffer=read_tempfile(filename);
printf("client message:%s %s\n",filename,buffer);
free(buffer);
close(client_sockfd);
}
}
#endif
#if 0
/*
* client端程序:
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
void write_tempfile(const char *filename,char*buffer,size_t length){
int fd;
fd=open(filename,O_WRONLY);
write(fd,&length,sizeof(length));
write(fd,buffer,length);
close(fd);
}
int main() {
int sockfd;
int len;
struct sockaddr_in address;
int result;
char *buffer="Hello world oooookkk";
size_t length=strlen(buffer)+1;
char filename[]="/home/hfz/tmp/temp_file.axx";
size_t flen=strlen(filename)+1;
sockfd = socket(AF_INET,SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = 9734;
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *) &address, len);
if (result == -1) {
perror("连接失败");
return 1;
}
write_tempfile(filename,buffer,length);
write(sockfd,&flen,sizeof(flen));
write(sockfd, filename, flen);
printf("Message sent to server:%s \n", filename);
close(sockfd);
return 0;
}
#endif
#if 0
/*
* getopt示例2:
* 5. 利用getopt类似的函数对命令行参数进行解析
*/
#include <stdlib.h>
#include <stdio.h>
//#include <unistd.h>
#include <getopt.h>
const char *program_name;
void print_usage(FILE*stream,int exit_code){
fprintf(stream,"Usage:%s [options]\n",program_name);
fprintf(stream,
"-a argument Use 1\n"
"-b argument Use 2\n"
"-c Use 3\n"
"-d Use 4\n"
"-e Use 5\n");
exit(exit_code);
}
int main(int argc,char*argv[]){
char *servername=getenv("SERVERNAME");
char *options="a:b::cde";
int ch;
program_name=argv[0];
if(argc==1){
print_usage(stdout,0);
}
if(servername==NULL)
{
while((ch=getopt(argc,argv,options))!=-1){
printf("optind:%d\n",optind);
printf("optarg:%s\n",optarg);
printf("ch:%c\n",ch);
switch(ch)
{
case 'a':
printf("option a:'%s'\n",optarg);
servername="a.com";
break;
case 'b':
printf("option b:'%s'\n",optarg);
servername="b.com";
break;
case 'c':
printf("option c\n");
servername="c.com";
break;
case 'd':
printf("option d\n");
servername="d.com";
break;
case 'e':
printf("option e\n");
servername="e.com";
break;
default:
printf("unknown option:%c\n",ch);
servername="localhost.localmain";
break;
}
printf("optopt+%c\n",optopt);
}
}
printf("servername:%s\n",servername);
return 0;
}
#endif
#if 0
/*
* 示例程序二:
*/
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
const char *program_name;
void print_usage(FILE* stream,int exit_code){
fprintf(stream,"Usage: %s options [inputfile ...]\n",program_name);
fprintf(stream,
"-h --help Display this usage information.\n"
"-o --output filename Write output to file.\n"
"-v --verbose Print verbose messages.\n");
exit(exit_code);
}
int main(int argc,char *argv[])
{
int next_option;
const char* const short_options="ho:v";
const struct option long_options[]={
{"help",0,NULL,'h'},
{"output",1,NULL,'o'},
{"verbose",0,NULL,'v'},
{NULL,0,NULL,0},
};
const char*output_filename=NULL;
int verbose=0;
program_name=argv[0];
if(argc==1){
print_usage(stdout,0);
}
do{
next_option=getopt_long(argc,argv,short_options,long_options,NULL);
switch(next_option){
case 'h':
print_usage(stdout,0);
case 'o':
output_filename=optarg;
break;
case 'v':
verbose=1;
break;
case '?':
print_usage(stderr,1);
case -1:
break;
default:
abort();
}
}while(next_option!=-1);
if(verbose){
int i;
for(i=optind;i<argc;++i)
printf("Argument:%s\n",argv[i]);
}
return 0;
}
#endif
#if 0
/*
* 6. 多线程并发问题:信号量的使用
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NLOOP 5000
int counter;
pthread_mutex_t counter_mutex=PTHREAD_MUTEX_INITIALIZER;
void* doit(void*);
int main()
{
pthread_t tidA,tidB;
pthread_create(&tidA,NULL,doit,NULL);
pthread_create(&tidB,NULL,doit,NULL);
pthread_join(tidA,NULL);
pthread_join(tidB,NULL);
return 0;
}
void *doit(void*vptr)
{
int i,val;
for(i=0;i<NLOOP;i++)
{
pthread_mutex_lock(&counter_mutex);
val=counter;
printf("%x:%d\n",(unsigned int)pthread_self(),val+1);
counter=val+1;
pthread_mutex_unlock(&counter_mutex);
}
return NULL;
}
#endif
#if 0
/*
* 7. 生产者消费者问题
*/
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define NUM 5
int queue[NUM];
sem_t blank_num,product_num;
void *producer(void *arg)
{
int p=0;
while(1){
sem_wait(&blank_num);
queue[p]=rand()%1000+1;
printf("Produce %d\n",queue[p]);
sem_post(&product_num);
p=(p+1)%NUM;
sleep(rand()%5);
}
}
void *consumer(void *arg)
{
int c=0;
while(1){
sem_wait(&product_num);
printf("Consume %d\n",queue[c]);
queue[c]=0;
sem_post(&blank_num);
c=(c+1)%NUM;
sleep(rand()%5);
}
}
int main()
{
pthread_t pid,cid;
sem_init(&blank_num,0,NUM);
sem_init(&product_num,0,0);
pthread_create(&pid,NULL,producer,NULL);
pthread_create(&pid,NULL,consumer,NULL);
pthread_join(pid,NULL);
pthread_join(cid,NULL);
sem_destroy(&blank_num);
sem_destroy(&product_num);
return 0;
}
#endif
#if 0
/*
* 示例程序2:
*/
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
struct msg{
struct msg*next;
int num;
};
struct msg *head;
pthread_cond_t has_product=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *consumer(void*p)
{
struct msg*mp;
for(;;){
pthread_mutex_lock(&lock);
while(head==NULL)
pthread_cond_wait(&has_product,&lock);
mp=head;
head=mp->next;
pthread_mutex_unlock(&lock);
printf("Consume %d\n",mp->num);
free(mp);
sleep(rand()%5);
}
}
void *producer(void*p)
{
struct msg *mp;
for(;;){
mp=malloc(sizeof(struct msg));
mp->num=rand()%1000+1;
printf("Produce %d\n",mp->num);
pthread_mutex_lock(&lock);
mp->next=head;
head=mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand()%5);
}
}
int main()
{
pthread_t pid,cid;
srand(time(NULL));
pthread_create(&pid,NULL,producer,NULL);
pthread_create(&cid,NULL,consumer,NULL);
pthread_join(pid,NULL);
pthread_join(cid,NULL);
return 0;
}
#endif
#if 0
/*
* 8. 子进程的生成
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
pid_t child;
if((child=fork())<0){
perror("fork");
exit(EXIT_FAILURE);
}
else if(child==0){
puts("in child");
printf("child pid=%d\n",getpid());
printf("child ppid=%d\n",getppid());
exit(EXIT_SUCCESS);
}
else{
puts("in parent");
printf("parent pid=%d\n",getpid());
printf("parent ppid=%d\n",getppid());
exit(EXIT_SUCCESS);
}
}
#endif
#if 0
/*
* 9. 获取IP地址
*/
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
int main()
{
struct addrinfo *res,*pt;
struct sockaddr_in *sinp;
const char *addr;
char abuf[INET_ADDRSTRLEN];
int succ=0,i=0;
char a[50];
scanf("%s",a);
succ=getaddrinfo(a,NULL,NULL,&res);
if(!succ)
{
printf("ERROR!\n");
exit(succ);
}
for(pt=res,i=0;pt!=NULL;pt=pt->ai_next,i++)
{
sinp=(struct sockaddr_in*)pt->ai_addr;
addr=(const char*)inet_ntop(AF_INET,&sinp->sin_addr,abuf,INET_ADDRSTRLEN);
printf("%2d.IP=%s\n",i,addr);
}
return EXIT_SUCCESS;
}
#endif
/*
* 1. 遍历目录-1
*/
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
void show_directory(char* path)
{
DIR *dir;
struct dirent*entry;
static int count=0;
int i=0;
int j=0;
if(NULL==(dir=opendir(path)))
printf("error opening dir\n");
else {
chdir(path);
// system("pwd");
count+=1;
while(entry=readdir(dir))
{
// if(strcmp(entry->d_name,".")==0||
// strcmp(entry->d_name,"..")==0)
if((entry->d_name)[0]=='.')
continue;
i=0;
j=0;
switch(entry->d_type){
case DT_DIR:
while(i++<count)
printf("+");
printf("\e[32;44m%s\e[0m\n",entry->d_name );
show_directory(entry->d_name);
break;
case DT_REG:
while(j++<count+4)
printf("-");
printf("\e[30;41m%s\e[0m\n",entry->d_name );
break;
default:
printf("%s\n",entry->d_name );
break;
}
}
count-=1;
chdir("..");
closedir(dir);
}
}
int main(int argc,char**argv)
{
if(argc<2)
{
printf("Not enough arguments!\n");
return -1;
}
show_directory(argv[1]);
return 0;
}
#endif
#if 0
/*
* 遍历目录-2
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#define MAX_PATH 1024
void dirwalk(char *dir,void(*fcn)(char*))
{
char name[MAX_PATH];
struct dirent *dp;
DIR *dfd;
if((dfd=opendir(dir))==NULL) {
fprintf(stderr,"dirwalk:can't open %s\n",dir);
return ;
}
while((dp=readdir(dfd))!=NULL){
if(strcmp(dp->d_name,".")==0||
strcmp(dp->d_name,"..")==0)
continue;
if(strlen(dir)+strlen(dp->d_name)+2>sizeof(name))
fprintf(stderr,"dirwalk:name %s/%s too long\n",dir,dp->d_name);
else{
sprintf(name,"%s/%s",dir,dp->d_name);
printf("%s\n",name);
fcn(name);
}
}
closedir(dfd);
}
int main(int argc,char**argv)
{
char *dir;
if(argc<2){
fprintf(stderr,"Usage:dirwalk <dir>\n");
return 1;
}
dir=argv[1];
dirwalk(dir,dirwalk);
}
#endif
#if 0
/*
* 遍历目录-3
*/
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir, pwd[2]=".";
if (argc != 2)
topdir=pwd;
else
topdir=argv[1];
printf("Directory scan of %s:\n",topdir);
printdir(topdir,0);
printf("------done-------\n");
return (0);
}
#endif
#if 0
/*
* 2. 利用管道进行读写
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void writer(const char *message,int count,FILE* stream)
{
for(;count>0;--count)
{
fprintf(stream,"%s\n",message);
fflush(stream);
sleep(1);
}
}
void reader(FILE*stream)
{
char buffer[1024];
while(!feof(stream)&&!ferror(stream)
&&fgets(buffer,sizeof(buffer),stream)!=NULL)
{
fputs(buffer,stdout);
}
}
int main()
{
int fds[2];
pid_t pid;
pipe(fds);
pid=fork();
if(pid==(pid_t)0){
FILE *stream;
close(fds[1]);
stream=fdopen(fds[0],"r");
reader(stream);
close(fds[0]);
}
else{
FILE *stream;
close(fds[0]);
stream=fdopen(fds[1],"w");
writer("Hello,world.",10,stream);
close(fds[1]);
}
}
#endif
#if 0
/*
* 3. 利用stat来获得系统文件的相关信息
*/
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc,char**argv)
{
struct stat buf;
mode_t mode;
char type[80];
int fd;
if(argc!=2){
puts("Usage:mstat {file}");
exit(EXIT_FAILURE);
}
if((fd=open(argv[1],O_RDONLY))<0){
perror("open");
exit(EXIT_FAILURE);
}
if((fstat(fd,&buf))<0){
perror("open");
exit(EXIT_FAILURE);
}
mode=buf.st_mode;
printf(" FILE:%s\n",argv[1]);
printf(" INODE:%ld\n",buf.st_ino);
printf(" DEVICE:%d,%d\n",major(buf.st_dev),
minor(buf.st_dev));
printf(" MODE:%#o\n",mode&~(S_IFMT));
printf(" LINKS:%d\n",buf.st_nlink);
printf(" UID:%d\n",buf.st_uid);
printf(" GID:%d\n",buf.st_gid);
if(S_ISLNK(mode))
strcpy(type,"Symbolic line");
else if(S_ISREG(mode))
strcpy(type,"Regular file");
else if(S_ISDIR(mode))
strcpy(type,"Directory");
else if(S_ISCHR(mode))
strcpy(type,"Character device");
else if(S_ISBLK(mode))
strcpy(type,"Block device");
else if(S_ISFIFO(mode))
strcpy(type,"FIFO");
else if(S_ISSOCK(mode))
strcpy(type,"Socket");
else
strcpy(type,"Unknown type");
printf(" TYPE:%s\n",type);
printf(" SIZE:%ld\n",buf.st_size);
printf("BLK SIZE:%ld\n",buf.st_blksize);
printf(" BLOCKS:%d\n",(int)buf.st_blocks);
printf("ACCESSED:%s",ctime(&buf.st_atime));
printf("MODIFIED:%s",ctime(&buf.st_mtime));
printf(" CHANGED:%s",ctime(&buf.st_ctime));
if(close(fd)<0){
perror("close");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
#endif
#if 0
/*
* 4. 利用socket进行通信
* server端程序:
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
char* read_tempfile(const char *filename){
int fd;
size_t length;
char *buffer;
fd=open(filename,O_RDONLY);
lseek(fd,0,SEEK_SET);
read(fd,&length,sizeof(size_t));
buffer=malloc(length);
read(fd,buffer,length);
close(fd);
return buffer;
}
int main()
{
char*buffer;
char filename[200];
int length;
int fd;
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 9734;
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *) &server_address, server_len);
listen(server_sockfd, 5);
while (1) {
printf("Server is waiting ....\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *) &client_address,
(socklen_t *__restrict) &client_len);
read(client_sockfd, &length, sizeof(length));
read(client_sockfd,filename,length);
buffer=read_tempfile(filename);
printf("client message:%s %s\n",filename,buffer);
free(buffer);
close(client_sockfd);
}
}
#endif
#if 0
/*
* client端程序:
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
void write_tempfile(const char *filename,char*buffer,size_t length){
int fd;
fd=open(filename,O_WRONLY);
write(fd,&length,sizeof(length));
write(fd,buffer,length);
close(fd);
}
int main() {
int sockfd;
int len;
struct sockaddr_in address;
int result;
char *buffer="Hello world oooookkk";
size_t length=strlen(buffer)+1;
char filename[]="/home/hfz/tmp/temp_file.axx";
size_t flen=strlen(filename)+1;
sockfd = socket(AF_INET,SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = 9734;
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *) &address, len);
if (result == -1) {
perror("连接失败");
return 1;
}
write_tempfile(filename,buffer,length);
write(sockfd,&flen,sizeof(flen));
write(sockfd, filename, flen);
printf("Message sent to server:%s \n", filename);
close(sockfd);
return 0;
}
#endif
#if 0
/*
* getopt示例2:
* 5. 利用getopt类似的函数对命令行参数进行解析
*/
#include <stdlib.h>
#include <stdio.h>
//#include <unistd.h>
#include <getopt.h>
const char *program_name;
void print_usage(FILE*stream,int exit_code){
fprintf(stream,"Usage:%s [options]\n",program_name);
fprintf(stream,
"-a argument Use 1\n"
"-b argument Use 2\n"
"-c Use 3\n"
"-d Use 4\n"
"-e Use 5\n");
exit(exit_code);
}
int main(int argc,char*argv[]){
char *servername=getenv("SERVERNAME");
char *options="a:b::cde";
int ch;
program_name=argv[0];
if(argc==1){
print_usage(stdout,0);
}
if(servername==NULL)
{
while((ch=getopt(argc,argv,options))!=-1){
printf("optind:%d\n",optind);
printf("optarg:%s\n",optarg);
printf("ch:%c\n",ch);
switch(ch)
{
case 'a':
printf("option a:'%s'\n",optarg);
servername="a.com";
break;
case 'b':
printf("option b:'%s'\n",optarg);
servername="b.com";
break;
case 'c':
printf("option c\n");
servername="c.com";
break;
case 'd':
printf("option d\n");
servername="d.com";
break;
case 'e':
printf("option e\n");
servername="e.com";
break;
default:
printf("unknown option:%c\n",ch);
servername="localhost.localmain";
break;
}
printf("optopt+%c\n",optopt);
}
}
printf("servername:%s\n",servername);
return 0;
}
#endif
#if 0
/*
* 示例程序二:
*/
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
const char *program_name;
void print_usage(FILE* stream,int exit_code){
fprintf(stream,"Usage: %s options [inputfile ...]\n",program_name);
fprintf(stream,
"-h --help Display this usage information.\n"
"-o --output filename Write output to file.\n"
"-v --verbose Print verbose messages.\n");
exit(exit_code);
}
int main(int argc,char *argv[])
{
int next_option;
const char* const short_options="ho:v";
const struct option long_options[]={
{"help",0,NULL,'h'},
{"output",1,NULL,'o'},
{"verbose",0,NULL,'v'},
{NULL,0,NULL,0},
};
const char*output_filename=NULL;
int verbose=0;
program_name=argv[0];
if(argc==1){
print_usage(stdout,0);
}
do{
next_option=getopt_long(argc,argv,short_options,long_options,NULL);
switch(next_option){
case 'h':
print_usage(stdout,0);
case 'o':
output_filename=optarg;
break;
case 'v':
verbose=1;
break;
case '?':
print_usage(stderr,1);
case -1:
break;
default:
abort();
}
}while(next_option!=-1);
if(verbose){
int i;
for(i=optind;i<argc;++i)
printf("Argument:%s\n",argv[i]);
}
return 0;
}
#endif
#if 0
/*
* 6. 多线程并发问题:信号量的使用
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NLOOP 5000
int counter;
pthread_mutex_t counter_mutex=PTHREAD_MUTEX_INITIALIZER;
void* doit(void*);
int main()
{
pthread_t tidA,tidB;
pthread_create(&tidA,NULL,doit,NULL);
pthread_create(&tidB,NULL,doit,NULL);
pthread_join(tidA,NULL);
pthread_join(tidB,NULL);
return 0;
}
void *doit(void*vptr)
{
int i,val;
for(i=0;i<NLOOP;i++)
{
pthread_mutex_lock(&counter_mutex);
val=counter;
printf("%x:%d\n",(unsigned int)pthread_self(),val+1);
counter=val+1;
pthread_mutex_unlock(&counter_mutex);
}
return NULL;
}
#endif
#if 0
/*
* 7. 生产者消费者问题
*/
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define NUM 5
int queue[NUM];
sem_t blank_num,product_num;
void *producer(void *arg)
{
int p=0;
while(1){
sem_wait(&blank_num);
queue[p]=rand()%1000+1;
printf("Produce %d\n",queue[p]);
sem_post(&product_num);
p=(p+1)%NUM;
sleep(rand()%5);
}
}
void *consumer(void *arg)
{
int c=0;
while(1){
sem_wait(&product_num);
printf("Consume %d\n",queue[c]);
queue[c]=0;
sem_post(&blank_num);
c=(c+1)%NUM;
sleep(rand()%5);
}
}
int main()
{
pthread_t pid,cid;
sem_init(&blank_num,0,NUM);
sem_init(&product_num,0,0);
pthread_create(&pid,NULL,producer,NULL);
pthread_create(&pid,NULL,consumer,NULL);
pthread_join(pid,NULL);
pthread_join(cid,NULL);
sem_destroy(&blank_num);
sem_destroy(&product_num);
return 0;
}
#endif
#if 0
/*
* 示例程序2:
*/
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
struct msg{
struct msg*next;
int num;
};
struct msg *head;
pthread_cond_t has_product=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *consumer(void*p)
{
struct msg*mp;
for(;;){
pthread_mutex_lock(&lock);
while(head==NULL)
pthread_cond_wait(&has_product,&lock);
mp=head;
head=mp->next;
pthread_mutex_unlock(&lock);
printf("Consume %d\n",mp->num);
free(mp);
sleep(rand()%5);
}
}
void *producer(void*p)
{
struct msg *mp;
for(;;){
mp=malloc(sizeof(struct msg));
mp->num=rand()%1000+1;
printf("Produce %d\n",mp->num);
pthread_mutex_lock(&lock);
mp->next=head;
head=mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand()%5);
}
}
int main()
{
pthread_t pid,cid;
srand(time(NULL));
pthread_create(&pid,NULL,producer,NULL);
pthread_create(&cid,NULL,consumer,NULL);
pthread_join(pid,NULL);
pthread_join(cid,NULL);
return 0;
}
#endif
#if 0
/*
* 8. 子进程的生成
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
pid_t child;
if((child=fork())<0){
perror("fork");
exit(EXIT_FAILURE);
}
else if(child==0){
puts("in child");
printf("child pid=%d\n",getpid());
printf("child ppid=%d\n",getppid());
exit(EXIT_SUCCESS);
}
else{
puts("in parent");
printf("parent pid=%d\n",getpid());
printf("parent ppid=%d\n",getppid());
exit(EXIT_SUCCESS);
}
}
#endif
#if 0
/*
* 9. 获取IP地址
*/
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
int main()
{
struct addrinfo *res,*pt;
struct sockaddr_in *sinp;
const char *addr;
char abuf[INET_ADDRSTRLEN];
int succ=0,i=0;
char a[50];
scanf("%s",a);
succ=getaddrinfo(a,NULL,NULL,&res);
if(!succ)
{
printf("ERROR!\n");
exit(succ);
}
for(pt=res,i=0;pt!=NULL;pt=pt->ai_next,i++)
{
sinp=(struct sockaddr_in*)pt->ai_addr;
addr=(const char*)inet_ntop(AF_INET,&sinp->sin_addr,abuf,INET_ADDRSTRLEN);
printf("%2d.IP=%s\n",i,addr);
}
return EXIT_SUCCESS;
}
#endif