1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <signal.h>
#include <sys/wait.h>
void wait_sem (int i_sig)
{
}
int main (void)
{
int *zone;
int memid;
int semid;
pid_t pid1;
pid_t pid2;
union semun argument;
struct sigaction wait_incr;
sigset_t all;
key_t key;
memid = shmget (IPC_PRIVATE, 100, IPC_CREAT);
pid1 = getpid ();
if (memid == -1)
{
perror ("UNABLE TO CREATE THE SHARED MEMORY\n");
return (EXIT_FAILURE);
}
wait_incr.sa_handler = wait_sem;
sigemptyset (&wait_incr.sa_mask);
sigemptyset (&all);
key = ftok ("/path/file.x", 'E');
semid = semget (key, 1, IPC_EXCL | SEM_R | SEM_A | IPC_CREAT);
if (semid == -1)
{
perror ("UNABLE TO CREATE THE SEMAPHORE\n");
return (EXIT_FAILURE);
}
zone = shmat (memid, NULL, 0);
zone[0] = 34;
printf ("process pid1 = %d & zone[0] = %d\n", pid1, zone[0]++);
pid2 = fork ();
if (pid2 < 0)
{
perror ("FORK HAS FAILED\n");
return (EXIT_FAILURE);
}
/* child's process */
else if (pid2 == 0)
{
pid2 = getpid ();
argument.val = 0;
semctl (semid, 0, SETVAL, argument);
while (1)
{
if (semctl (semid, 0, GETVAL, argument) == 1)
{
sigaction (SIGUSR1, &wait_incr, (struct sigaction *) 0);
printf ("process pid2 = %d & zone[0] = %d\n", pid2, zone[0]++);
semctl (semid, 0, SETVAL, argument);
kill (pid1, SIGUSR1);
sigsuspend (&all);
}
}
return (EXIT_SUCCESS);
}
/* father's process */
else
{
argument.val = 1;
semctl (semid, 0, SETVAL, argument);
while (1)
{
if (semctl (semid, 0, GETVAL, argument) == 0)
{
sigaction (SIGUSR1, &wait_incr, (struct sigaction *) 0);
printf ("process pid1 = %d & zone[0] = %d\n", pid1, zone[0]++);
semctl (semid, 0, SETVAL, argument);
kill (pid2, SIGUSR1);
sigsuspend (&all);
}
}
}
return (EXIT_SUCCESS);
} |
Partager