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
|
#include <stdio.h>
#include <string.h> /* Needed for the strcat function. */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h> /* Needed for the wait function. */
#include <unistd.h> /* needed for the fork function. */
#define SHMSIZE 25
int main()
{
char *shm;
int n; /* Variable to get the user's number into the program. */
int shmid;
while (n != 'q') // Request user for input numbers until the use presses 'q' to quit (the entire program I guess?).
{
if(fork() == 0) // Parent of fork.
{
shmid = shmget(2009, SHMSIZE, 0);
shm = shmat(shmid, 0, 0);
char *s = (char *) shm;
*s = '\0'; /* Set first location to string terminator, for appending later. */
{
printf("Please enter a number, E.g., 10: ");
scanf("%d", &n);
sprintf(s, "%s%d", s, n); /* Append number to string. */
strcat(s, "\n"); /* Append newline. */
printf ("\nParent wrote %s\n", shm);
shmdt(shm);
}
}
else // Child of fork.
{
/* Variable s removed, as wasn't used. */
/* Removed first call to wait, as it held up parent process. */
shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
shm = shmat(shmid, 0, 0);
wait(NULL);
printf ("Child read %s\n", shm);
shmdt(shm);
shmctl(shmid, IPC_RMID, NULL);
}
}
return 0;
}
|