问题
Here is a very small "kill" related program .The program is executing but am unable to figure out the code.Can any one please make me understand the code below.
int main(int argc ,char **argv)
{
if(argc < 2)
{
printf("usage : ./kill PID");
return -1;
}
kill(atoi(argv[1]),SIGKILL);
return 0;
}
回答1:
Basically, it just checks to see if an argument has been provided. if(argc < 2)
means are there less than two arguments to the program. Note that the program name itself is an argument too, which is why it's argc < 2
and not argc < 1
. Once this has been determined the builtin kill
function is called. The first argument to this method is an integer, which is why the second argument (the PID, represented as a string) is parsed to an integer with atoi
. The second argument to kill
is the signal, in this case SIGKILL
. Other signals, such as SIGHUP
could also have been used, but since this program "kills", it uses SIGKILL
.
回答2:
it takes the first argument to the program (argv[1]
), converts it to an integer (atoi
- ascii to integer) and sends the SIGKILl (9) signal to the process with that process id.
if(argc < 2)
simply checks if there were enough parameters provided, and return -1
exits the program with an exit code != 0
to signal unsuccessful termination.
来源:https://stackoverflow.com/questions/4134848/unable-to-understand-the-kill-program-of-linux