Question

I'm trying to write my own C shell. I'm wondering how to make calling 'kill' in the command line work. For example,

shell> kill 2      
shell: process 2 has been killed

Line 1 is user input 'kill 2'

Line 2 is program-printed message of what has been done.

I know I have to take the pid as the argument I believe and send the SIGKILL signal. Using something like

 kill(pid, SIGKILL);

How do I connect this kill function to respond when a user inputs 'kill 2' in a C implementation? I guess I'm having a hard time connecting it to the command line arguments for implementation. I might need strtok/atoi? Thank you.

Was it helpful?

Solution 2

#include<stdio.h>
#include<sys/types.h>
#include<signal.h>

int main(int argc, char **argv)
{
    if (argc < 3)
    {
        printf("usage: ./kill OPERATION(kill/cont) PID\n");
        return -1;
    }

    if(strcmp(argv[1],"kill") == 0 )
    {
        printf("Kill:\n");
        kill(atoi(argv[2]), SIGKILL);
    }
    else  if(strcmp(argv[1],"cont") == 0)
    {
        printf("cont:\n");
        kill(atoi(argv[2]), SIGCONT);
    }
    else
    {
        printf("Kill default:\n");
        kill(atoi(argv[2]), SIGKILL);
    }

    return 0;
}

OTHER TIPS

Better you go for "getopt" which might look as fallows,

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <signal.h>

int pid;
if((pid = getopt(argc, argv, "0123456789")) != -1)
    if(isdigit(pid)){
        if(kill(pid, SIGKILL) == -1){
            perror("KILL:");
            exit(0);
        }
    }else{
        printf("Input format: kill <pid>");
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top