if (listen(sockfd, 5 )) {
perror("listen");
exit(1);
}
for (;;)
{
addrlen2 = sizeof(peer);
newsockfd = accept(sockfd, &peer , &addrlen2);
if ( newsockfd < 0) {
perror("accept");
exit(1);
}
if (fork() == 0) {
close(sockfd);
/* process request */
printf("connection on socket %d from %sn", newsockfd, inet_ntoa(peer.sin_addr.s_addr));
process(newsockfd);
close(newsockfd);
exit(0);
}
close(newsockfd);
}
}
3,共享内存编程例子
例子1:
#include
#include
#include
#define SHMKEY 74
#define K 1024
int shmid;
cleanup()
{
shmctl(shmid,IPC_RMID,0);
exit(0);
}
main()
{
int *pint;
char *addr1,*addr2;
extern char *shmat();
extern cleanup();
for (i=0;i<20;i)
signal(i,cleanup);
shmid=shmget(SHMKEY,128*K,0777|IPC_CREAT);
addr1=shmat(shmid,0,0);
addr2=shmat(shmid,0,0);
printf("addr1 0x%x addr2 0x%xn",addr1,addr2);
pint=(int*)addr1;
for (i=0;i<256;i)
*pint=i;
pint=(int*)addr1;
*pint=256;
pint=(int*)addr2;
for (i=0;i<256;i)
printf("index %dtvalue%dn",i,*pint);
shmdt(addr1);
shmdt(addr2);
pause();
}
例子2
1),创建和写共享内存:
/* Includes */
#include
#include
#include
#include
#include
#include
#include
typedef struct
{
int tc_number;
char ap_name[5];
char mymessage[20];
} COMM_TABLE;
main()
{
/* local variables */
int ret= 0;
key_t key;
int i;
int shm_id;
int found = 0;
COMM_TABLE *comm_reg;
key = ftok(".","w");
/* create a share memory if not exist */
if ((shm_id = shmget(key ,sizeof(COMM_TABLE),IPC_CREAT|IPC_EXCL|0666)) == -1)
{
/* share memory has been created */
if ((shm_id = shmget(key , sizeof(COMM_TABLE),0)) == -1)
{
printf("error = %dn", errno);
return (ret);
}
}
comm_reg = (COMM_TABLE *) shmat(shm_id, (char *) 0, SHM_SHARE_MMU);
comm_reg->tc_number= 56110563;
}
2), 读共享内存,再删除共享内存:
/* Includes */
#include
#include
#include
#include
#include
#include
#include
typedef struct
{
int tc_number;
char ap_name[5];
char mymessage[20];
} COMM_TABLE;
main()
{
/* local variables */
int ret= 0;
key_t key;
int i;
int shm_id;
int found = 0;
COMM_TABLE *comm_reg;
char * pointer;
key = ftok(".","w");
/* share memory has been created */
if ((shm_id = shmget(key , sizeof(COMM_TABLE),0)) == -1)
{
printf("error = %dn", errno);
return (ret);
}
comm_reg = (COMM_TABLE *) shmat(shm_id, (char *) 0, SHM_SHARE_MMU);
printf("tc number=%d!!!n", comm_reg->tc_number);
/* kill share memory */
shmctl(shm_id,IPC_RMID,0);
推荐阅读
- 2 SCO UNIX讲座
- 班门弄斧 用机十天之体验
- SCO UNIX系统故障特征、分析及解决
- 在Unix终端上实现多屏功能
- 口令篇 UNIX系统的安全
- super试飞首信V851之一:初步印象篇
- unixware和unix openserver比较二
- Cisco路由器配置信息在Unix下的备份、恢复与更新
- SCO UNIX基础讲座--第十二讲:使用 TCP/IP
- 明日之后中获得钢铁入侵抗击者纪念币具体操作方法