//code7-3-b.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#define BUF_SIZE 1024
int shmid;
char *shmptr;
void ipc_rmid_handler(int s)
{
if ((shmctl(shmid, IPC_RMID, NULL)) == -1) {
perror("shmctl");
exit(1);
}
printf("\n");
shmdt(shmptr);
exit(0);
}
int main(void)
{
key_t key;
key = ftok("/etc/passwd", 0);
if (key == -1) {
perror("ftok");
exit(1);
}
if ((shmid = shmget(key, BUF_SIZE,
IPC_CREAT | 0666)) == -1) {
perror("shmget");
printf("shmget error\n");
exit(1);
}
if ((shmptr = (char *)shmat(shmid,
NULL, 0)) == ((void *)(-1))) {
perror("shmat");
fprintf(stderr, "shmat error\n");
exit(1);
}
while(1) {
signal(SIGINT, ipc_rmid_handler);
signal(SIGQUIT, ipc_rmid_handler);
printf("input string: ");
scanf("%s", shmptr);
printf("\n");
}
exit(0);
}
|