[英]Trying to use execvp to execute external commands in C (in a shell like program)
[英]Shell Commands in C (Error using Execvp)
我想運行以下命令“ ls | date”,但是每當我隔離ls和日期時,它們都不會使用execvp執行。
問題:
Isolated:ls
ls: impossible to acess 'ld-linux-x86-64.so.2': Unknown directory or file
ls: impossible to acess 'ld-linux-x86-64.so.2': Unknown directory or file
Isolated: date
ls: impossible to acess 'date': Unknown directory or file
在代碼中,我要檢查“;” 但是當我勾選“” &&“ |” 它隔離了我想要的參數...但是它們無法運行。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
char command_line[256]="ls | date";
char *ptr_current_command;
char *saveptr1;
char *saveptr2;
char *saveptr3;
char *ptr_current_parameter;
char *ptr_current_parameter2;
char *str[256];
int i=0;
int wait_child;
pid_t pid;
//Uses Strtok to recognize token ";"
ptr_current_command=strtok_r(command_line, ";", &saveptr1);
while (ptr_current_command != NULL) {
//printf("current_command: %s\n", ptr_current_command);
//Uses Strtok to recognize token " "
ptr_current_parameter=strtok_r(ptr_current_command, " ", &saveptr2);
while(ptr_current_parameter != NULL){
//printf("\tcurrent_parameter: %s\n", ptr_current_parameter);
//Uses Strtok to recognize token "|"
ptr_current_parameter2=strtok_r(ptr_current_parameter, "|", &saveptr3);
while(ptr_current_parameter2 != NULL){
printf("\t\tIsolei: %s\n", ptr_current_parameter2);
str[i]=ptr_current_parameter2;
i++;
//Closes token by token until final NULL of "|"
ptr_current_parameter2=strtok_r(NULL, "|", &saveptr3);
}
pid=fork();
if (pid < 0) { perror("fork"); exit(errno); }
if (pid == 0){
execvp(str[0], str);
perror("execvp"); exit(errno);
}
if (wait_child)
waitpid(pid, NULL, 0);
//Fecha Delimitador Espaço
ptr_current_parameter=strtok_r(NULL, " ", &saveptr2);
}
//Closes token by token until final NULL of ";"
ptr_current_command=strtok_r(NULL, ";", &saveptr1);
}
return 0;
}
這里有兩個問題。
首先,您沒有正確構建str
。 它必須在最后一個參數之后包含一個NULL
指針值,否則execvp
將不知道哪個選項是最后一個。
由於str
是未初始化的,因此除您在內部設置的元素之外的任何元素的內容都是未定義的。 嘗試讀取這些元素(就像execvp
一樣)會調用未定義的行為 。
內循環之后,您需要將當前索引設置為NULL
。
第二個問題是,進入內循環時,您不會將i
重置為0。 因此,即使第一個命令起作用,第二個命令也不會起作用,因為它一直在寫第一個命令的參數。
修復后,您的內部循環應如下所示:
i = 0; // reset i for each command
while(ptr_current_parameter2 != NULL){
printf("\t\tIsolei: %s\n", ptr_current_parameter2);
str[i]=ptr_current_parameter2;
i++;
//Closes token by token until final NULL of "|"
ptr_current_parameter2=strtok_r(NULL, "|", &saveptr3);
}
str[i] = NULL; // terminate the list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.