execvp - 为什么我的程序会退出?

3

我正在执行一个程序,将输入解析为一个数组并在其上运行函数。代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>

// arglist - a list of char* arguments (words) provided by the user
// it contains count+1 items, where the last item (arglist[count]) and
//    *only* the last is NULL
// RETURNS - 1 if should cotinue, 0 otherwise
int process_arglist(int count, char** arglist);

void main(void) {
    while (1) {
        char **arglist = NULL;
        char *line = NULL;
        size_t size;
        int count = 0;

        if (getline(&line, &size, stdin) == -1)
            break;

        arglist = (char**) malloc(sizeof(char*));
        if (arglist == NULL) {
            printf("malloc failed: %s\n", strerror(errno));
            exit(-1);
        }
        arglist[0] = strtok(line, " \t\n");

        while (arglist[count] != NULL) {
            ++count;
            arglist = (char**) realloc(arglist, sizeof(char*) * (count + 1));
            if (arglist == NULL) {
                printf("realloc failed: %s\n", strerror(errno));
                exit(-1);
            }      
            arglist[count] = strtok(NULL, " \t\n");
        }

        if (count != 0) {
            if (!process_arglist(count, arglist)) {
                free(line);
                free(arglist);
                break;
            }
        }
        free(line);
        free(arglist);
    }
    pthread_exit(NULL);
}

我的职责是:

int process_arglist(int count, char** arglist) {
    int i;
    for (i = 0; i < count; i++) {
        //printf("%s\n", arglist[i]);
        execvp(arglist[0], arglist);
    }
}

在仅打印名称(已标记)时,程序没有终止。但是当我尝试使用execvp后,它在一次迭代后停止了。有人可以告诉我原因以及该怎么做吗?


这可能是重复的。 - chqrlie
void main(void) 应该改为 int main(void) - chqrlie
1
你查过 execvp 的作用吗? - user253751
1
你的问题中的 [fork] 标签在呼喊着:“问题就在于你没有在代码中使用我!” - Kaz
1个回答

3

这不是一个bug,而是程序应该运行的方式。 execvp 会替换当前进程为新的进程,但保留一些文件句柄。

如果你想启动一个新的进程,你必须使用 fork() 在子进程中调用 execvp()

请查看 fork()execvp() 的手册。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接