我想创建一个程序,它会接受一个 Linux 输入命令,比如 pwd -P 并用它做一些事情。我想要做的是把它们放在一个字符串中,其中空格''字符被替换为空终止符'\0',所以它看起来像“pwd\0-P”。然后,我可以让 array[0] 指向字符串的开头,并让 array[1] 指向 '\0' 之后的部分,所以我会有 2 个单独的字符串 -> array[0] = " pwd" 和数组 [1] = "-P"。这就是我可以使用 exec(array[0],array);
我的问题是,当我这样做时,空终止符不会在“pwd”之后终止字符串,并且我的字符串最终变成“pwd-P”,其中没有空格。
我正在做这一切的字符串是“检查”
int main(int argc, char * argv[]) {
char ch;
pid_t pid;
int i=0;
int flag = 0;
int word = 0;
int count = 0;
char check[100],temp[100];
char * array[100];
printf("Your Command> ");
strcpy(check,"");
//command stuff
array[word] = check;
temp[i]='\0';
while((ch = getchar()) != '\n'){
count = count+1;
if(ch != '&' && ch != ' '){
strcpy(temp,&ch);
strcat(check,temp);
}
else if(ch == ' '){
check[count] = '\0';
word = word+1;
array[word] = &check[count];
}
else if(ch == '&'){
flag =1;
check[count] = 0;
}
}
//end of command stuff
if(flag!=1){
check[count] = '\0';
}
word = word+1;
puts(check);
array[word] = &check[count];
//fork process stuff
if((pid = fork())==0){
printf("hello from child\n");
printf("%s\n",array[0]);
printf("%s\n",array[1]);
printf("%s\n",array[2]);
execvp(array[0], array);
}
else{
if(flag == 0){
wait(NULL);
printf("hello from parent\n");
}
else{
printf("hello from parent (no wait)\n");
}
}
return(EXIT_SUCCESS);
}