Hello All,
In a pthread application, I need to call system() to execute
an external program. When system() is called in a non-main thread, any
other calls to system() are blocked until the previous call has returned. How
do we work around the blocking?
A very simple sample program which demonstrates the behavior
follows:
==========================================================================
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void * do_thread(void * arg)
{
printf("0x%x-
start\n", (int)pthread_self());
system("echo
sleep start; sleep 1; echo sleep done");
printf("0x%x-
stop\n", (int)pthread_self());
return NULL;
}
int main(int argc, char **argv)
{
int numThreads=10;
int pass;
pthread_t
tid[numThreads];
void * retVal;
pthread_attr_t
attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,
0);
printf
("starting threads\n");
for (pass=0;
pass<numThreads; pass++)
{
pthread_create(&tid[pass],
&attr, do_thread, NULL);
}
for (pass=0;
pass<numThreads; pass++)
{
pthread_join(tid[pass],
&retVal);
}
return 0;
}
==========================================================================
Output from the above sample is:
==========================================================================
starting threads
0xb0081000- start
0xb0103000- start
0xb0185000- start
0xb0207000- start
0xb0289000- start
0xb030b000- start
0xb038d000- start
0xb040f000- start
0xb0491000- start
0xb0513000- start
sleep start
sleep done
0xb0081000- stop
sleep start
sleep done
0xb0103000- stop
sleep start
sleep done
0xb0185000- stop
sleep start
sleep done
0xb0207000- stop
sleep start
sleep done
0xb0289000- stop
sleep start
sleep done
0xb030b000- stop
sleep start
sleep done
0xb0491000- stop
sleep start
sleep done
0xb040f000- stop
sleep start
sleep done
0xb038d000- stop
sleep start
sleep done
0xb0513000- stop
==========================================================================
In this sample, all calls to system() in the separate
threads are serialized by the system() call (which I do not want).
It is compiled and executed on a 10.5.8 Intel dual-quad machine
with gcc version 4.0.1 using the following:
gcc exec.c -pthread -o exec
Thanks in advance,
Mark