IPC in Unix of POSIX Standard
IPC in Unix of POSIX Standard
IPC in Unix of POSIX Standard
o/p:
sarat@ubuntu:~$ cc 3.1.c
sarat@ubuntu:~$ ./a.out
Enter some text: sarat
Enter some text: y8cs224
Enter some text: sujit
Enter some text: end
sarat@ubuntu:~$ ipcs
------ Message Queues --------
key msqid owner perms used-bytes messages
0x000000e0 0 sarat 666 3072 6
o/p:
sarat@ubuntu:~$ cc 3.2.c
sarat@ubuntu:~$ ./a.out
You wrote: sarat
You wrote: y8cs224
You wrote: sujit
You wrote: end
/* semint.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
union semun {
int val; /* used for SETVAL only */
struct semid_ds *buf; /* for IPC_STAT and IPC_SET */
ushort *array; /* used for GETALL and SETALL */
};
int main(void)
{
key_t key;
int semid;
union semun arg1;
if ((key = ftok("semdemo.c", 'J')) == -1) {
perror("ftok");
exit(1);
}
/* create a semaphore set with 1 semaphore: */
if ((semid = semget(key, 1, 0666 | IPC_CREAT)) == -1) {
perror("semget");
exit(1);
}
/* initialize semaphore #0 to 1: */
arg1.val = 1;
if (semctl(semid, 0, SETVAL, arg1) == -1) {
perror("semctl");
exit(1);
}
return 0;
}
/* semdemo.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main(void)
{
key_t key;
int semid;
struct sembuf sb = {0, -1, 0}; /* set to allocate resource */
if ((key = ftok("semdemo.c", 'J')) == -1) {
perror("ftok");
exit(1);
}
/* grab the semaphore set created by seminit.c: */
if ((semid = semget(key, 1, 0)) == -1) {
perror("semget");
exit(1);
}
printf("Press return to lock: ");
getchar();
printf("Trying to lock...\n");
if (semop(semid, &sb, 1) == -1) {
perror("semop");
exit(1);
}
printf("Locked.\n");
printf("Press return to unlock: ");
getchar();
sb.sem_op = 1; /* free resource */
if (semop(semid, &sb, 1) == -1) {
perror("semop");
exit(1);
}
printf("Unlocked\n");
return 0;
}
/* semrm.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main(void)
{
key_t key;
int semid;
union semun arg;
if ((key = ftok("semdemo.c", 'J')) == -1) {
perror("ftok");
exit(1);
}
/* grab the semaphore set created by seminit.c: */
if ((semid = semget(key, 1, 0)) == -1) {
perror("semget");
exit(1);
}
/* remove it: */
if (semctl(semid, 0, IPC_RMID, arg) == -1) {
perror("semctl");
exit(1);
}
return 0;
}