[英]Run an external program as a thread instead of a process
I want to be able to run an external program as a pthread rather than as a separate process in C. How would I, for example, change the following program to use threads? 我希望能够将外部程序作为pthread而不是C中的单独进程来运行。例如,如何更改以下程序以使用线程?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
// ...other code
int main () {
char* command[] = {"/bin/ls", NULL};
pid_t pid = fork();
if (pid == 0) {
execv(command[0], command);
} else {
wait(NULL);
}
return 0;
}
This question doesn't make a lot of sense, as the major difference between a process and a thread is that threads share a single memory space, and an external program cannot do that. 这个问题没有多大意义,因为进程和线程之间的主要区别在于线程共享一个内存空间,而外部程序则无法做到这一点。 You might want to load a dynamic library or have two processes map a shared memory object, if you want them to share memory.
如果希望它们共享内存,则可能要加载动态库或让两个进程映射共享内存对象。
A way to run an external program from a child thread without replacing the process, though, is with popen()
. 但是,从子线程运行外部程序而不替换进程的一种方法是使用
popen()
。
For your specific case, where you want to run shell commands, system() function call can be used in threads, eliminating need to create child process. 对于您的特定情况,要运行shell命令,可以在线程中使用system()函数调用,而无需创建子进程。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#define MAX_COUNT 10 // Change MAX_COUNT as per maximum number of commands possible
void ThreadFunc(char *command)
{
int ret = 0;
if (NULL == command)
{
printf("ERROR::Input pointer argument is NULL\n");
return;
}
if ('\0' == command[0])
{
printf("ERROR::Input command string is EMPTY\n");
return;
}
ret = system(command);
if (0 != ret)
{
printf("ERROR::system(%s) failed. errno=%d\n", command, errno);
}
else
{
printf("SUCCESS::system(%s) succeeded\n", command);
}
}
int main ()
{
char* command[] = {"/bin/ls", NULL};
int i = 0;
int count = 0;
int ret = 0;
pthread_t threadId[MAX_COUNT]; // Change MAX_COUNT as per maximum number of commands possible
while (NULL != command[i])
{
ret = pthread_create(&threadId[i], NULL, (void *(*)(void *))ThreadFunc, (void *)command[i]);
if (0 != ret)
{
printf("ERROR::pthread_create() failed for command %s. errno = %d\n", command[i], errno);
}
else
{
printf("SUCCESS::pthread_create() succeeded for command %s\n", command[i]);
count++; // update i
}
i++;
}
// pthread_join to wait till all thread are finished
for (i = 0; i < count; i++)
{
pthread_join(threadId[i], NULL);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.