當前正在接收輸入linux shell命令的程序,並執行它們來創建子進程。從用戶輸入獲取shell命令並執行C程序
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char * argv[])
{
int pid, status;
if (argc < 2) {
printf("Usage: %s command, [arg1 [arg2]...]\n", argv[0]);
return EXIT_FAILURE;
}
printf("Starting %s...\n", argv[1]);
pid = fork();
if (pid == 0) {
execvp(argv[1], &argv[1]);
perror("execvp");
return EXIT_FAILURE; // Never get there normally
} else {
if (wait(&status) == -1) {
perror("wait");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
作品與像./program command arg
輸入,但需要與例如ARGS接收各種命令:./program command arg command arg .....
任何建議?
但我想讓用戶使用任意數量的命令與參數,當然,我將不得不改變,如果(argc> 2),但不知道如何處理,而不知道用戶命令的數量想要輸入。 – Devoid 2011-05-05 20:43:16
你要麼需要通過它們作爲單一,引用參數(如:'./program「命令ARG ARG」「命令2 ARG ARG」'),然後分析每個字符串,或拿出一個分隔符,讓你知道當一個命令/ ARG設置完成(通過'argv'迭代) – 2011-05-05 20:57:08
其實......你可能* *能夠與getopt的()來做到這一點,它已經有一段時間...尋找 – 2011-05-05 21:01:36