【问题标题】:execvp - why does my program exit? [duplicate]execvp - 为什么我的程序退出? [复制]
【发布时间】:2015-12-19 22:59:10
【问题描述】:

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

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

【问题讨论】:

  • 这可能是重复的。
  • void main(void) 应该是int main(void)
  • 你查过execvp 做什么吗?
  • 你问题中的[fork]标签在喊,“问题是你没有在任何地方的代码中使用我!”

标签: c fork


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多