0

I'm testing the execl() function tho I'm not being able to solve how to make the printf() after the execl() show up when I run the program. I figured out it has something to do with the fflush() function, although I still can't do it. Heres the code.

#include<sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>

void main(){
    printf ("Show content from directory /:\n");
    execl( "/bin/ls", "ls", "-l", "/", NULL );
    fprintf (stdout,"End of command: ls -l /\n");
    fflush(stdout);
}
Pablo
  • 13,271
  • 4
  • 39
  • 59
  • 7
    You never return from an `exec*()` call, except if it fails. – prog-fh Nov 27 '19 at 17:27
  • 4
    It won't show up unless `execl()` fails. The `exec()` family of functions literally completely replace the current process. See https://stackoverflow.com/questions/4204915/please-explain-the-exec-function-and-its-family (I'll let others decide if this is a duplicate of that question.) – Andrew Henle Nov 27 '19 at 17:27
  • 2
    Do you know what `execl()` does? Do you know how very, very different it is from `system()`? (You probably want `system()`.) – Steve Summit Nov 27 '19 at 17:27
  • 1
    If you don't want to replace the current process, call `execl()` in a child process created with `fork()`. Then use `wait()` in the parent to wait for it to finish. – Barmar Nov 27 '19 at 17:31

1 Answers1

2

From the man page https://linux.die.net/man/3/execl

Return Value The exec() functions only return if an error has occurred. The return value is -1, and errno is set to indicate the error.

If you really want to use execl() instead of system(), then you should change the code like this.

#include<sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>

int main(void){
    printf ("Show content from directory /:\n");

    pid_t p=fork(); // create a child process
    if(p==0) // if we are in the child process
    {
      execl( "/bin/ls", "ls", "-l", "/", NULL ); // replace it with a new program
      perror("execl"); // reaching this line is necessarily a failure
      exit(1); // terminate child process in any case
    }
    waitpid(p, NULL, 0); // wait for child process to terminate

    fprintf (stdout,"End of command: ls -l /\n");
    fflush(stdout);
    return 0;
}
prog-fh
  • 13,492
  • 1
  • 15
  • 30