我正在执行一个程序,将输入解析为一个数组并在其上运行函数。代码如下:
#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)
。 - chqrlieexecvp
的作用吗? - user253751[fork]
标签在呼喊着:“问题就在于你没有在代码中使用我!” - Kaz