I am writing a program where a parent process ( which later on becomes daemon process) creates a child process and then this child furthers creates multiple threads which run concurrently to process queries. This requires threads to communicate with daemon process via child process and then the daemon process sends back control messages back to the thread via the child process. I have written the following code for that.
typedef struct shared SHAREDM;
struct shared{
char tmsg[500];
char pmsg[500];
} shrd_tc,*shrd_pc;
int main(){
initialize();
int pid;
int shmID;
int status;
shmID = shmget(IPC_PRIVATE, sizeof(SHAREDM), IPC_CREAT | 0666);
if (shmID < 0) {
printf("*** shmget error (server) ***\n");
exit(1);
}
shrd_pc = (SHAREDM*) shmat(shmID, NULL, 0); //shared memory b/w parent process and child process
pid=fork();
int st=0;
if(pid<0){
printf("\n Error ");
exit(1);
}
/*
*Child will create threads that will run queries concurrently and communicate to parent process (daemon)
via child process
* child and threads communcate through shared memory 'shared_tc' of type SHAREDM
* parent(daemon) and child also communicate through shared memory 'shared_pc' of type SHAREDM
*/
else if(pid==0) {
pthread_t threads[20];
long taskids[20];
for(int i=0;i<20;i++){
taskids[i]=i+1;
pthread_create( &threads[i], NULL, query, (void*)taskids[i]);
}
int t=10;
while(t--){
printf("Hello from child\n");
// child will check continuously whether daemon has written in the shared memory
printf("%s\n", shrd_pc->pmsg);
//child will check continuouly whether threads has written something in the shared memory
printf("%s\n", shrd_tc.tmsg);
sleep(1);
}
for(int i=0;i<20;i++){
pthread_join(threads[i],NULL);
}
}
else{
//unmask the file mode
umask(0);
int sid;
//set new session
sid = setsid();
if(sid < 0){
// Return failure
exit(1);
}
// Change the current working directory to root.
chdir("/");
// Close stdin. stdout and stderr
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
int t=10;
while(t--){
//doemon will write continuous in shared memory
sprintf(shrd_pc->pmsg,"%s","Hello I am parent process");
sleep(1);
}
}
return 0;
}
void* query(void* thread_id){
long tid=(long)thread_id;
int T=10;
while(T--){
//printf("Hello from thread %ld\n",tid);
//thread writing something to shared memory between child and threads
sprintf(shrd_tc.tmsg,"%s %ld","Hello I am thread ",tid);
sleep(1);
}
pthread_exit(0);
}
When I am trying to get daemon process write something to shrd_pc->pmsg it's not able to do so. I am not able to read that shrd_pc->pmsg in child process. How do I get this daemon process to write at shrd_pc->pmsg so that later on child can read the same?