Reputation: 25
I need to compile a program with system, i have the name of the archive, and the name of the execute file, the son execute gcc -o file.c exe1 and the father execute ./exe1 for example
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
if (argc != 3) {
printf("Debe ingresar el nombre del archivo a compilar y el ejecutable");
exit(1);
} else {
char *archivo1 = strcat("gcc ", argv[1]);
char *archivo2 = strcat(archivo1, ".c -o ");
char *archivo3 = strcat(archivo2, argv[2]);
char *ejecutable = strcat("./", argv[2]);
pid_t pid_hijo;
int valor;
switch(pid_hijo = fork()) {
case -1:
printf("No se pudo crear el hijo");
case 0:
valor = system(archivo3);
default:
wait(NULL);
valor = system(ejecutable);
}
}
return 0;
}
Upvotes: 0
Views: 71
Reputation: 53006
This
char *archivo1=strcat("gcc ",argv[1]);
is undefined behavior.
In c "gcc "
is a string literal and it's read only, strcat()
will try to write to it and actually beyond the end of "gcc "
, trying to write beyond the end of an array is also undefined behavior, but in this case it's not an array so it's illegal from any point of view.
You need snprintf()
instead, like this
char command[200];
ssize_t result;
result = snprintf(command, sizeof(command), "gcc %s -o %s", argv[1], argv[2]) ;
if (result >= (ssize_t) sizeof(command))
error_cannot_store_the_command_in_command():
Upvotes: 2