Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing a program in C linux using fork and exec

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;
}
like image 634
user3392539 Avatar asked Oct 21 '25 21:10

user3392539


2 Answers

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

like image 65
Yama Avatar answered Oct 23 '25 12:10

Yama


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

like image 43
Rahul R Dhobi Avatar answered Oct 23 '25 12:10

Rahul R Dhobi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!