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

标签 c fork

<分区>

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

#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 时,它会在一次迭代后停止。谁能告诉我为什么以及该怎么做?

最佳答案

这不是错误,这是它应该工作的方式。 execvp 用新进程替换当前进程,保持一些文件句柄打开。

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

检查 fork()execvp() 的手册页。

关于c - execvp - 为什么我的程序退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376282/

相关文章:

c - 结构末尾未命名位域的用途是什么

c - 数组作为函数的参数

c - Ubuntu 终端不显示所有值

c - 两个 child 之间的生产者消费者 fork [C]

C: 用 scanf fork

c++ - 标识特殊方法的编译器/解释器阶段的名称?

c - C 中的 While 循环不执行

c - 失效进程,fork()

node.js - 如何让我的 nodejs 应用程序服务于多个用户?

bash:包含 fork 进程的脚本在通过反引号执行时挂起