/*************** 进程A ****************/
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
int main(){
// 1.生成键值key
key_t key = ftok( "/home/yj/Desktop/fork_test.c", 'A');
if( key == -1 ){
fprintf( stderr, "ftok error,errno=%d,%s",
errno, strerror(errno));
return 1;
}
// 2.打开或创建共享内存
int shmid = shmget( key, 128, IPC_CREAT|0644);
if( shmid == -1 ){
fprintf( stderr, "shmid error,errno=%d,%s",
errno, strerror(errno));
return 2;
}
// 3.将物理内存地址映射到进程内
char *pshm = shmat( shmid, NULL, 0);
if( pshm == (void *)-1 ){
fprintf( stderr, "shmat error,errno=%d,%s",
errno, strerror(errno));
return 3;
}
// 4.设置有名信号量POSIX,实现进程间的同步通信
sem_t *psem = sem_open( "named_sem",O_CREAT, 0644, 0);
sprintf( pshm, "%d\n", getpid()); //往共享内存里面写入当前进程的id
sem_post(psem);
// 5.解除映射
shmdt(pshm);
while(1);
return 0;
}
/*************** 进程B ****************/
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
int main(){
// 1.生成键值key
key_t key = ftok( "/home/yj/Desktop/fork_test.c", 'A');
if( key == -1 ){
fprintf( stderr, "ftok error,errno=%d,%s",
errno, strerror(errno));
return 1;
}
// 2.打开或创建共享内存
int shmid = shmget( key, 128, IPC_CREAT|0644);
if( shmid == -1 ){
fprintf( stderr, "shmid error,errno=%d,%s",
errno, strerror(errno));
return 2;
}
// 3.将物理内存地址映射到进程内
char *pshm = shmat( shmid, NULL, 0);
if( pshm == (void *)-1 ){
fprintf( stderr, "shmat error,errno=%d,%s",
errno, strerror(errno));
return 3;
}
// 4.打开有名信号量POSIX,实现进程间的同步通信获得进程A的进程id
sem_t *psem = sem_open( "named_sem", O_CREAT, 0644, 0);
sem_wait(psem);
int A_id = atoi(pshm);
printf( "%d\n", A_id);
// 5.解除映射
shmdt(pshm);
while(1);
return 0;
}