I'm executing a program that parses the input to an array and runs function on it. the code is:
#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);
}
and my function is:
int process_arglist(int count, char** arglist) {
int i;
for (i = 0; i < count; i++) {
//printf("%s\n", arglist[i]);
execvp(arglist[0], arglist);
}
}
when just printed the names (marked), it did not terminate. but when I try to use execvp, it stops after one iteration. Can someone tell me why and what to do?
This is not a bug, it is the way it is supposed to work. execvp replaces the current process with the new process, keeping some of the file handles open.
If you want to launch a new process, you must use fork() and call execvp() in the child process.
Check the man pages for fork() and execvp().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With