1

I have a question, I used the following program(fork() functions) to create a child process to overload another program using execl(). If I want to use echo command in the execl() functions or other kinds of exec() functions ,what should I do? I use following program, but it failed! the terminal gave me a warning:echo: cannot access hello world!: No such file or directory this is parent!

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

   int main()
   {   pid_t childpid;
       childpid=fork();

       if(childpid==-1){
           perror("failed to fork");
           return 1;
           }
       if(childpid==0)
       {    
          execl("/bin/ls","echo","hello world!",NULL);
          perror("child failed to exec");
          return 1;
          }
       if(childpid!=wait(NULL)){
       perror("parent failed to wait due to signal or error");
       return 1;
       }
       sleep(5);
       printf("this is parent!\n");



       return 0;
   }
python3
  • 251
  • 4
  • 12
  • Basically, I just want to use echo command in the exec() function, and use exec() to overload main function, but I am not sure how to use execl() function to perform echo command. I think maybe there is something wrong with the path? – python3 Sep 24 '15 at 21:54
  • http://stackoverflow.com/questions/8827939/handling-arguments-array-of-execvp,I think this also can help me solve the problem! – python3 Sep 24 '15 at 22:31

1 Answers1

2

The command you are executing is:

/bin/ls "echo" "hello world!"

What you probably want to execute is (assuming you are using bash):

/bin/bash -c 'echo "hello world!"'

So use:

execl("/bin/bash","-c","echo \"hello world!\"",NULL);

And you probably want to check for errors before using perror.


Edit:

As per EOF's reccomendation you should probably use system call rather than exec. It handles creating the subprocess for you, and allows you to focus on the task at hand (namely invoking a shell command). The possible disadvantage is that it waits for the subprocess to die before continuing, but that's most likely not an issue (not in this case, anyway). It also ignores certain signals (SIGINT and SIGQUIT) which might not be desirable, depending on how you design your program.

mszymborski
  • 1,615
  • 1
  • 20
  • 28