Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a command from C and terminate it

Tags:

c++

c

linux

I have command like:

./mjpg_streamer -i "./input_uvc.so -n -f 15 -r 1280x720" -o "./output_http.so -n -w ./www "

for streaming video through Ethernet. Currently I am running through terminal, and for exit I just press Ctrl+c. But I need to do this using c-code. Is it possible or any other method available ?.

Thanks.

like image 907
Haris Avatar asked Dec 26 '22 21:12

Haris


2 Answers

Technically you can do what you need to do by using fork() and the exec family.

It may work like this:

 pid_t PID = fork();
 if(PID == 0) {
      execl("yourcommandhere");
      exit(1);
 }
 //do Whatever
 kill(PID, 15);  //Sends the SIGINT Signal to the process, telling it to stop.

execl (or any other member of the family, look here: http://linux.die.net/man/3/execl), will replace the current process with the process you're calling. This is the child process we created with fork. Fork returns '0' for the child process and the actual process ID of the child to the original process calling fork, which gives the original process control.

By calling kill and supplying SIGINT (15) you're telling the process with the specified PID (which you got from fork) to stop. exit(1) is necessary, because otherwise, if execl should fail, you'd have two processes doing the same thing at your hands. It's a failsafe.

I hope this helps.

like image 67
Refugnic Eternium Avatar answered Dec 28 '22 12:12

Refugnic Eternium


usaually we use system("command");

copy that Entire command into string lets say str

./mjpg_streamer -i "./input_uvc.so -n -f 15 -r 1280x720" -o "./output_http.so -n -w ./www "

Into string and then use

system(str); //in c code.
like image 33
Gangadhar Avatar answered Dec 28 '22 10:12

Gangadhar