[英]Getting user C String input into exec() function in c
这是一个普遍的问题:程序必须fork()
和wait()
才能使子项完成。 子exec()
将exec()
用户名为INPUT的另一个程序。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int status;
char input[BUFSIZ];
printf(">");
scanf("%s",input);
char *args[] = {"./lab1"};
pid_t pid = fork();
if(pid==0){
execvp(args[0],args);
}else if(pid<0){
perror("Fork fail");
}else{
wait(&status);
printf("My Child Information is: %d\n", pid);
}
return 0;
}
我的问题是让用户输入要运行的程序名称(在“>”提示符下),然后将该输入输入execvp(如果有人有任何想法,请输入另一个exec()函数)
我现在暂时不要责备您使用scanf("%s")
,尽管您应该知道这确实不是健壮的代码 。
您的基本任务是获取用户输入的字符数组,并以某种方式将其转换为适合传递给execvp
的字符指针数组。
您可以使用strtok
将输入字符串标记为用空格分隔的标记,并使用malloc/realloc
确保数组中有足够的元素来存储字符串。
或者,由于您已经存在潜在的缓冲区溢出问题,仅使用固定大小的数组可能就足够了。
例如,以下程序显示了一种实现方法,它使用固定的字符串echo my hovercraft is full of eels
,并将其标记化为适合执行:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static char *myStrDup (char *str) {
char *other = malloc (strlen (str) + 1);
if (other != NULL)
strcpy (other, str);
return other;
}
int main (void) {
char inBuf[] = "echo my hovercraft is full of eels";
char *argv[100];
int argc = 0;
char *str = strtok (inBuf, " ");
while (str != NULL) {
argv[argc++] = myStrDup (str);
str = strtok (NULL, " ");
}
argv[argc] = NULL;
for (int i = 0; i < argc; i++)
printf ("Arg #%d = '%s'\n", i, argv[i]);
putchar ('\n');
execvp (argv[0], argv);
return 0;
}
然后,它输出标记化的参数并执行它:
Arg #0 = 'echo'
Arg #1 = 'my'
Arg #2 = 'hovercraft'
Arg #3 = 'is'
Arg #4 = 'full'
Arg #5 = 'of'
Arg #6 = 'eels'
my hovercraft is full of eels
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.