2015-10-05 47 views
0

我希望能够运行一个外部程序作为一个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; 
} 
+3

描述你想要实现的 - 即你想运行它作为一个线程,因为... –

+0

发布的代码将最终失败。这是因为系统函数:'fork()'不能保证成功。 'fork()'有三种返回值:== 0(child)> 0(parent和<0(failure)。代码需要检查所有三个条件,而不是假设调用fork( )'成功了 – user3629249

+0

你知道如何使用线程吗?如果是这样,那么你唯一的问题是如何让线程执行一个shell命令 – user3629249

回答

2

这个问题并没有做出很大的意义,作为一个过程和线程之间的主要区别在于线程共享一个内存空间,以及一个外部程序无法做到这一点。如果您希望它们共享内存,您可能需要加载动态库或让两个进程映射共享内存对象。

从子线程运行外部程序而不替换进程的一种方法是使用popen()

1

对于您的特定情况,如果您想要运行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; 
} 
+1

系统调用创建一个子进程。 –

相关问题