1. popen:让进程看似文件
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
char buf[ 100 ];
int i = 0;
fp = popen("who|sort","r");
while ( fgets(buf, 100, fp) != NULL )
printf("%3d %s", i++, buf );
pclose( fp );
return 0;
}
程序输出:
leichaojian@ThinkPad-T430i:~$ cc popendemo.c
leichaojian@ThinkPad-T430i:~$ ./a.out
0 leichaojian :0 2014-09-02 22:38 (:0)
1 leichaojian pts/0 2014-09-02 23:01 (:0)
2. 一个简单的socket例子:时间服务器
服务器timeserv.c:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <strings.h>
#define PORTNUM 13000
#define HOSTLEN 256
#define oops(msg) {perror(msg);exit(1);}
int main( int ac, char *av[] )
{
struct sockaddr_in saddr;
struct hostent *hp;
char hostname[ HOSTLEN ];
int sock_id, sock_fd;
FILE *sock_fp;
char *ctime();
time_t thetime;
sock_id = socket( PF_INET, SOCK_STREAM, 0 );
if ( sock_id == -1 )
oops("socket");
bzero((void *)&saddr, sizeof(saddr));
gethostname(hostname, HOSTLEN);
hp = gethostbyname(hostname);
bcopy((void *)hp->h_addr, ( void *)&saddr.sin_addr, hp->h_length);
saddr.sin_port = htons(PORTNUM);
saddr.sin_family = AF_INET;
if ( bind(sock_id, (struct sockaddr *)&saddr, sizeof( saddr )) != 0 )
oops("bind");
if ( listen( sock_id, 1) != 0 )
oops("listen");
while ( 1 ){
sock_fd = accept( sock_id, NULL, NULL );
printf("wow!got a call!\n");
if ( sock_fd == -1 )
oops("accept");
sock_fp = fdopen(sock_fd, "w");
if ( sock_fp == NULL )
oops("fdopen");
thetime = time( NULL );
fprintf(sock_fp, "the time here is..");
fprintf( sock_fp, "%s", ctime(&thetime));
fclose( sock_fp );
}
return 0;
}
而客户端的代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define oops(msg) {perror(msg);exit(1);}
int main( int ac, char *av[] )
{
struct sockaddr_in servadd;
struct hostent *hp;
int sock_id, sock_fd;
char message[ BUFSIZ ];
int messlen;
sock_id = socket( AF_INET, SOCK_STREAM, 0);
if ( sock_id == -1 )
oops("socket");
bzero(&servadd, sizeof(servadd));
hp = gethostbyname(av[1]);
if ( hp == NULL)
oops(av[1]);
bcopy(hp->h_addr, (struct sockaddr*)&servadd.sin_addr, hp->h_length);
servadd.sin_port = htons(atoi(av[2]));
servadd.sin_family = AF_INET;
if(connect(sock_id, (struct sockaddr *)&servadd, sizeof(servadd)) != 0)
oops("connect");
messlen = read(sock_id, message, BUFSIZ);
if (messlen == -1 )
oops("read");
if ( write(1, message, messlen ) != messlen )
oops("write");
close( sock_id );
return 0;
}
服务端运行如下:
leichaojian@ThinkPad-T430i:~$ ./a.out&
[3] 12397
客户端为:
leichaojian@ThinkPad-T430i:~$ ./a.out ThinkPad-T430i 13000
the time here is..Wed Sep 3 00:00:15 2014
leichaojian@ThinkPad-T430i:~$ hostname
ThinkPad-T430i