4

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;
}
2
  • 3
    What do you expect /bin/echo to do? Commented Mar 14, 2014 at 10:52
  • I don't know. What to write? I was trying to understand it. Commented Mar 14, 2014 at 11:01

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

/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");

Comments

2

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")

1 Comment

Thanks. but could you please explain it in a bit more detail as I am doing it the first time.
2

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 ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.