quimica funcion execl c shell exec

funcion - cómo usar correctamente tenedor, exec, esperar



funcion system() (1)

Aquí hay una solución simple y legible:

pid_t parent = getpid(); pid_t pid = fork(); if (pid == -1) { // error, failed to fork() } else if (pid > 0) { int status; waitpid(pid, &status, 0); } else { // we are the child execve(...); _exit(EXIT_FAILURE); // exec never returns }

El niño puede usar el valor parent almacenado si necesita conocer el PID del padre (aunque no lo hago en este ejemplo). El padre simplemente espera que el niño termine. Efectivamente, el niño se ejecuta "sincrónicamente" dentro del padre y no hay paralelismo. El padre puede consultar el status para ver de qué manera salió el niño (con éxito, sin éxito o con una señal).

El shell que estoy escribiendo necesita ejecutar un programa que le haya dado el usuario. Aquí está la versión simplificada muy acortada de mi programa

int main() { pid_t pid = getpid(); // this is the parents pid char *user_input = NULL; size_t line_sz = 0; ssize_t line_ct = 0; line_ct = getline(&user_input, &line_sz, stdin); //so get user input, store in user_input for (;;) { pid_t child_pid = fork(); //fork a duplicate process pid_t child_ppid = getppid(); //get the child''s parent pid if (child_ppid == pid) //if the current process is a child of the main process { exec(); //here I need to execute whatever program was given to user_input exit(1); //making sure to avoid fork bomb } wait(); //so if it''s the parent process we need to wait for the child process to finish, right? } }

  1. ¿He descifrado el nuevo proceso y he comprobado si es un proceso secundario correctamente?
  2. ¿Qué ejecutivo podría usar aquí para lo que estoy tratando de hacer? ¿Cuál es la forma más sencilla?
  3. ¿Cuáles son mis argumentos para esperar? La documentación que estoy viendo no ayuda mucho.

Supongamos que el usuario podría ingresar algo como ls, ps, pwd

Gracias.

Editar:

const char* hold = strdup(input_line); char* argv[2]; argv[0] = input_line; argv[1] = NULL; char* envp[1]; envp[0] = NULL; execve(hold, argv, envp);