[英]Create arguments from command line and save in an array
我正在嘗試從命令行保存我的 arguments 及其參數,如下所示
./run cat hello.txt: grep left: wc -c
我想在不知道數量的情況下將數組中的每個參數分開如下:
char *cat_args[] = {"cat", "tests/nevermind", NULL};
char *grep_args[] = {"grep", "left", NULL};
char *cut_args[] = {"wc", "-c", NULL};
我怎樣才能做到這一點?
int nbProc = 2;
for (int i = 0; i < argc; i++){
if (strcmp(argv[i], ":") == 0){
nbProc++;
}
}
int indice_debut[nbProc-2];
int j = 0;
for (int i = 1; i < argc; i++){
if (strcmp(argv[i], ":") == 0){
argv[i] = NULL;
indice_debut[j] = i + 1;
j++;
}
}
有了這個,我可以得到indice_debut = {4,7}
因為有:
在第 4 和第 7 position。
我試圖這樣運行它,但沒有運氣,我這樣做是為了可以使用execvp
。
execvp(argv[indice_debut[0]], argv + indice_debut[0]);
謝謝
使用malloc()
動態分配指針數組。 最多可以有argc/2
命令,因為最壞的情況是交替word: word: word: ...
,所以分配那么多元素。 數組元素可以指向argv
的元素,您可以將:
參數替換為 null 指針以結束每個子命令。
int main(int argc, char **argv) {
if (argc < 2) {
printf("At least one command is required\n");
exit(1);
}
char **arg_arrays = malloc(argc/2 * sizeof *arg_arrays);
int array_index = 0;
int arg_index = 0;
while (arg_index < argc) {
arg_arrays[array_index++] = &argv[arg_index];
for (; arg_index < argc && strcmp(argv[arg_index], ":") != 0; arg_index++) {}
argv[arg_index] = NULL;
}
// Execute each of the subcommands
for (int i = 0; i < array_index; i++) {
pid_t pid = fork();
if (pid == 0) {
execvp(arg_arrays[i][0], arg_arrays[i]);
} else if (pid < 0) {
perror("fork");
exit(1);
}
}
// wait for all the subcommands to finish
while (wait(NULL) > 0) {}
}
這只是一個如何解析子命令並執行它們的簡單示例。 如果您想將 pipe 從一個命令轉移到下一個命令,則需要添加該代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.