c - 将用户 C 字符串输入到 c 中的 exec() 函数中

标签 c input exec fork c-strings

这是一个普遍的问题: 该程序必须 fork()wait() 才能让 child 完成。 child 将 exec() 另一个名称由用户输入的程序。

#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"),但你应该知道它真的不是 robust code .

这里的基本任务是获取用户输入的字符数组,并以某种方式将其转换为适合传递给 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

关于c - 将用户 C 字符串输入到 c 中的 exec() 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161137/

相关文章:

Ruby gets() 没有返回正确的字符串

javascript - 检查所有文本输入是否为空,是否使用 if/else 语句显示警报?

c - 如何在linux中使用execv系统调用?

c++ - 有什么方法可以增加一个字符吗?

相对于复活节及时计算事件

c++ - C浮点精度

c - select() 和 read() 在串行端口读取时超时,但之前的 write() 成功?

python - 使用输入文件对象从python中的文件中读取变量

c - fork+exec 没有 atfork 处理程序

php - 从 PHP 执行 Python 脚本