UNIX进程之间的通信( 四 )


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);

推荐阅读