How to execute a command from C and complete it

I have a command like:

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

for streaming video over Ethernet. I am currently running through the terminal, and to exit I just press Ctrl + c . But I need to do this with c code. Is this possible or any other method?

Thanks.

+4
source share
4 answers

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

It can work as follows:

  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 family member, see here: http://linux.die.net/man/3/execl ), replaces the current process with the process you are calling. This is a child process that we created with fork. Fork returns "0" for the child process and the actual process identifier for the child process in the original process, calling fork, which gives the original process control.

By calling kill and supplying SIGINT (15), you tell the process with the specified PID (which you got from fork) to stop. exit(1) necessary, because otherwise, if execl should fail, you will have two processes doing the same in your hands. It is faultless.

Hope this helps.

+7
source

Usually we use a system ("command");

copy the whole command into a string allows str

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

To string and then use

 system(str); //in c code. 
+1
source
 ./mjpg_streamer -i "./input_uvc.so -n -f 15 -r 1280x720" -o "./output_http.so -n -w ./www " pkill mjpg_stramer 

you can call pkill with system()

+1
source

when you executed using system(./mjpg_streamer)

Create a custom mjpg_streamer process

You can kill this process again with pkill(mjpg_streamer)

+1
source

Source: https://habr.com/ru/post/1499768/


All Articles