You are on page 1of 3

IV IT ISEM

Experiment-3

NETWORK PROGRAMMING LAB

08A61A1227
DATE:

Write a program to create an integer variable using shared memory concept and increment the variable simultaneously by two processes. Use semaphores to avoid race conditions. Program: #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <unistd.h> #include <string.h> #include <errno.h> int main(void) { pid_t pid; int *shared; int shmid; shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666); printf("Shared Memory ID=%u",shmid); if (fork() == 0) { shared = shmat(shmid, (void *) 0, 0); printf("Child pointer %u\n", shared); *shared=1; printf("Child value=%d\n", *shared); sleep(2);
SRI PRAKASH COLLEGE OF ENGINEERING PAGE NO:

IV IT ISEM

NETWORK PROGRAMMING LAB

08A61A1227

printf("Child value=%d\n", *shared); } else { shared = shmat(shmid, (void *) 0, 0); printf("Parent pointer %u\n", shared); printf("Parent value=%d\n", *shared); sleep(1); *shared=42; printf("Parent value=%d\n", *shared); sleep(5); shmctl(shmid, IPC_RMID, 0); } }

SRI PRAKASH COLLEGE OF ENGINEERING

PAGE NO:

IV IT ISEM

NETWORK PROGRAMMING LAB

08A61A1227

Output:

Result: The program is verified and required output is obtained.

SRI PRAKASH COLLEGE OF ENGINEERING

PAGE NO:

You might also like