對於您的特定情況,如果您想要運行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;
}
描述你想要實現的 - 即你想運行它作爲一個線程,因爲... –
發佈的代碼將最終失敗。這是因爲系統函數:'fork()'不能保證成功。 'fork()'有三種返回值:== 0(child)> 0(parent和<0(failure)。代碼需要檢查所有三個條件,而不是假設調用fork( )'成功了 – user3629249
你知道如何使用線程嗎?如果是這樣,那麼你唯一的問題是如何讓線程執行一個shell命令 – user3629249