B
bill
I have a need to create a child process that can access 2 variables
from the parent process. fork is out as that creates a copy of memory
as the child can't access the parents memory. I tried pthread_create
but the child process ends up with the value from when the thread was
created and the current value.
I modified the following code as a proof of concept using 1 variable
from https://computing.llnl.gov/tutorials/pthreads/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 50
void *PrintHello(void *threadid){
long tid;
sleep(5);
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[]){
pthread_t threads[NUM_THREADS];
int rc;
long t=3;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
t*=2;
}
sleep(10);
pthread_exit(NULL);
}
The output is
Hello World! It's me, thread #3!
and it should be
Hello World! It's me, thread #31!
I found http://www.cs.cf.ac.uk/Dave/C/node27.html which shows shard
memory but the client and server are two separate programs. That
doesn't work for my application.
So what is the best way for a child process to access the current
value of a variable from a parent process?
Thank you in advance.
from the parent process. fork is out as that creates a copy of memory
as the child can't access the parents memory. I tried pthread_create
but the child process ends up with the value from when the thread was
created and the current value.
I modified the following code as a proof of concept using 1 variable
from https://computing.llnl.gov/tutorials/pthreads/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 50
void *PrintHello(void *threadid){
long tid;
sleep(5);
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[]){
pthread_t threads[NUM_THREADS];
int rc;
long t=3;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
t*=2;
}
sleep(10);
pthread_exit(NULL);
}
The output is
Hello World! It's me, thread #3!
and it should be
Hello World! It's me, thread #31!
I found http://www.cs.cf.ac.uk/Dave/C/node27.html which shows shard
memory but the client and server are two separate programs. That
doesn't work for my application.
So what is the best way for a child process to access the current
value of a variable from a parent process?
Thank you in advance.