Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/sem.h>
- #include <sys/ipc.h>
- #include <sys/types.h>
- #include <sys/shm.h>
- #include <string.h>
- #include <errno.h>
- #define SHMSZ 10
- int main(int argc,char *argv[])
- {
- key_t key1 = 12345;
- int semid;
- unsigned short semval;
- int cnt = 5;
- struct sembuf wait, signal;
- wait.sem_num = 0;
- wait.sem_op = -1;
- wait.sem_flg = SEM_UNDO;
- signal.sem_num = 0;
- signal.sem_op = 1;
- signal.sem_flg = SEM_UNDO;
- semid = semget(key1,1,IPC_CREAT);
- semval = 1;
- semctl(semid,0,SETVAL,semval);
- int shmid; // shared memory segment ID
- key_t key = 5678; // key for shared memory
- char *shm, *s; // pointers to shared memory
- if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
- perror("shmget");
- exit(1);
- }
- if ((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) {
- perror("shmat");
- exit(1);
- }
- int childpid = fork();
- int messageSentFully = 1;
- int messageReceivedFully = 1;
- if(childpid == 0){
- //printf("Process2 \n");
- while(1){
- semop(semid,&wait,1);
- if ( messageReceivedFully == 1)
- {
- puts("\nReceived message:");
- }
- char msg[SHMSZ] = {0};
- s = shm;
- for (int i = 0; i < SHMSZ; ++i)
- {
- msg[i] = s[i];
- }
- write(STDOUT_FILENO, msg, SHMSZ);
- if ( strcmp( msg, "quit\n") == 0 )
- {
- break;
- }
- if ( msg[SHMSZ-1] == 0 )
- {
- messageReceivedFully = 1;
- }
- else
- {
- messageReceivedFully = 0;
- }
- semop(semid,&signal,1);
- }
- semctl(semid,0,IPC_RMID);
- printf("Semaphore removed from the System = %s\n", strerror(errno));
- }
- else
- {
- while(1)
- {
- semop(semid,&wait,1);
- if (messageSentFully == 1)
- {
- puts("\nEnter message:");
- }
- char msg[SHMSZ] = {0};
- int bytesRead = read( STDIN_FILENO, msg, SHMSZ );
- if (bytesRead < SHMSZ)
- {
- messageSentFully = 1;
- }
- else
- {
- messageSentFully = 0;
- }
- s = shm;
- for (int i = 0; i < SHMSZ; ++i)
- {
- s[i] = msg[i];
- }
- if ( strcmp(msg, "quit\n") == 0 )
- {
- break;
- }
- semop(semid,&signal,1);
- }
- }
- shmdt((void*)shm);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement