How to kill background process from system functio

2019-06-21 09:47发布

问题:

How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

const char app[] = "fooprocess &";
system(app);

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.

回答1:

To interact with the process you need its PID. I'm not sure if it's possible with system but one alternative is to fork the process yourself using fork + exec.



回答2:

You absolutely cannot use system("foo &"); to create background processes that you can later monitor/kill. Any such use has a gigantic inherent bug: even if you know the pid, there is no way to tell if the process with that pid is the process you originally ran, or a completely different process that happened to get the same pid later.

To solve this problem (and countless other problems you don't want to think about or it will make your head hurt) you should forget you ever learned about the system function and create your child processes with fork and exec, or posix_spawn. This will result in a direct child process (your current method is creating grandchildren which get orphaned and taken in by the init process) which you can wait/waitpid on, and until you perform a wait operation, the child process's pid belongs to you and cannot be reused, so it's safe to send signals to it, etc.



回答3:


I have tried your problem using this:

ps -axc|grep -i myApp|awk '{print $1}' | tr -d '\n' | xargs -0 kill  

you can place that in system() like so:

system("ps -axc|grep -i myApp|awk '{print $1}' | tr -d '\n' | xargs -0 kill");

That will work.