Hey all!
Long time reader, first time poster!
So I'm trying to communicated between two processes on a UNIX machine using shared memory. I believe everything in this program is working fine except for how I'm attempting to call the memory to check.
Basically the parent process writes to the shared memory and says "How are you my child?" and the child process checks the shared memory and if the question is there it writes an answer of "I am fine, thanks!" but my check isn't nearly correct.
The attempted code I used was if (("%s",shared_memory) == "How are you my child?") but that's not correct cause it's skipping the if statement and moving to the else. How can I properly check the shared memory?
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
pid_t pid;
/* the identifier for the shared memory segment */
int segment_id;
/* a pointer to the shared memory segment */
char *shared_memory;
/* the size (in bytes) of the shared memory segment */
const int segment_size = 4096;
/** allocate a shared memory segment */
segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR);
/** attach the shared memory segment */
shared_memory = (char *) shmat(segment_id, NULL, 0);
printf("shared memory segment %d attached at address %p\n", segment_id, shared_memory);
sprintf(shared_memory, "How are you my child?"); //Parent writes
printf("*Currently written in memory: %s*\n", shared_memory);
/* fork another process */
pid = fork();
if (pid == 0)/* child process */
{
if (("%s",shared_memory) == "How are you my child?")
{
/** write a message to the shared memory segment */
sprintf(shared_memory, "I am fine thank you!");
pause();
}
}
else/* parent process */
{
usleep(100);//wait(NULL);
/** now detach the shared memory segment */
if (shmdt(shared_memory) == -1)
{
fprintf(stderr, "Unable to detach\n");
}
/** now remove the shared memory segment */
shmctl(segment_id, IPC_RMID, NULL);
}
return 0;
}
Thanks a bunch!
Namaste,
-Ray-