【发布时间】:2018-02-09 04:12:47
【问题描述】:
我正在编写一个程序,其中父进程(后来成为守护进程)创建一个子进程,然后该子进程进一步创建多个线程,这些线程同时运行以处理查询。这需要线程通过子进程与守护进程通信,然后守护进程通过子进程将控制消息发送回线程。我为此编写了以下代码。
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);
}
当我试图让守护进程向 shrd_pc->pmsg 写入内容时,它无法这样做。我无法在子进程中读取 shrd_pc->pmsg。如何让这个守护进程写入 shrd_pc->pmsg 以便稍后孩子可以读取相同的内容?
【问题讨论】:
-
你刚才叫我锄头吗?
-
当我删除了将父进程作为守护进程的过程时它工作正常。我写的逻辑不正确吗?
标签: c multithreading parent-child daemon