2015-10-05 51 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

系統調用創建一個子進程。 –

相關問題