executing a program in C linux using fork and exec

21,193

Solution 1

/bin/echo msg.c will print msg.c as output if you need to execute your msg binary then you need to change your code to execv("path/msg");

Solution 2

argv[0] contains your program's name and you are Echo'ing it. Works flawlessly ;-)

Solution 3

your exec executes the program echo which prints out whatever argv's value is;
furthermore you cannot "execute" msg.c if it is a sourcefile, you have to compile (gcc msg.c -o msg) it first, and then call something like exec("msg")

Solution 4

C programs are not executables (unless you use an uncommon C interpreter).

You need to compile them first with a compiler like GCC, so compile your msg.c source file into a msg-prog executable (using -Wall to get all warnings and -g to get debugging info from the gcc compiler) with:

gcc -Wall -g msg.c -o msg-prog

Take care to improve the msg.c till you get no warnings.

Then, you might want to replace your execv in your source code with something more sensible. Read execve(2) and execl(3) and perror(3). Consider using

execl ("./msg-prog", "msg-prog", "Foo is my name", NULL);
perror ("execl failed");
exit (127);

Read Advanced Linux Programming.

NB: You might name your executable just msg instead of msg-prog ....

Share:
21,193
user3392539
Author by

user3392539

Updated on July 05, 2022

Comments

  • user3392539
    user3392539 almost 2 years

    I want to execute a C program in Linux using fork and exec system calls. I have written a program msg.c and it's working fine. Then I wrote a program msg1.c.

    When I do ./a.out msg.c, it's just printing msg.c as output but not executing my program.

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h> /* for fork */
    #include <sys/types.h> /* for pid_t */
    #include <sys/wait.h> /* for wait */
    
    int main(int argc,char** argv)
    {
    /*Spawn a child to run the program.*/
        pid_t pid=fork();
        if (pid==0)
        { /* child process */
        //      static char *argv[]={"echo","Foo is my name.",NULL};
                execv("/bin/echo",argv);
                exit(127); /* only if execv fails */
        }
        else
        { /* pid!=0; parent process */
               waitpid(pid,0,0); /* wait for child to exit */
        }
     return 0;
    }
    
  • user3392539
    user3392539 about 10 years
    Thanks. but could you please explain it in a bit more detail as I am doing it the first time.