2

I am developing my application in C, and when application starts it needs to kill shell script which runs from system startup.

Here is my function that kills shell script from C++:

void Kill_Script_sh(void)
{
    FILE *fp;
    char buffer[30];
    char pid_number[5];
    int pid;
    int fd;
    std::stringstream command;

    command.str("");
    fp = popen("ps aux | grep tick.sh", "r");

    fgets(buffer, 30, fp);

    pclose(fp);

    pid_number[0] = buffer[11];
    pid_number[1] = buffer[12];
    pid_number[2] = buffer[13];
    pid_number[3] = buffer[14];
    pid_number[4] = buffer[15];


    pid = atoi(pid_number);

    printf("%d \n", pid);

    command << "sudo kill " << pid;

    system(command.str().c_str());
}

After I killed the process I need to check if it still exists. Is this correct way to do what I need? Any idea is helpful. Thanks

  • 6
    That's not C, that's C++. – molbdnilo Sep 29 '15 at 07:56
  • Have you tried your `ps` command line ? Chances are that your `grep` is matched as well, resulting in your killing the `grep` instead of the script. – marcolz Sep 29 '15 at 07:57
  • 1
    @molbdnilo it is mixed. –  Sep 29 '15 at 08:08
  • @Zola There's no such thing. It's either one or the other. – molbdnilo Sep 29 '15 at 08:12
  • @molbdnilo there is, because this is an app for embedded systems, it is compiled with g++ and everything is okay. –  Sep 29 '15 at 08:15
  • You are using 4 digits for the PID. Are you sure it's a good idea? [Under Linux](http://stackoverflow.com/questions/6294133/maximum-pid-in-linux) the default maximum PID is 32768. **If you forget one digit you will kill the wrong process!!** – Fabio says Reinstate Monica Sep 29 '15 at 08:18
  • @FabioTurati I am aware of that, but this situation with parsing ps aux is little shaky, thats the reason I asked for ideas to do this on the other way. –  Sep 29 '15 at 08:25
  • Have you considered using a PID file? (i.e, a file containing your script's PID, preferably with a `flock` held for the duration) – Hasturkun Sep 29 '15 at 08:44
  • I'm finding the PID number of my process correctly, only problem is checking if its still alive. @Hasturkun –  Sep 29 '15 at 08:49
  • There is only one way under standard UNIX to safely check if a child process ended, and that is by letting it's **parent** test this! Any other approch ends up in a race for PIDs. Do you have by any means the possibility to adjust/add the/a process spawing `wdt_tick.sh`? – alk Sep 29 '15 at 18:12

1 Answers1

1

After killing it (or in general), you can check for existence of a process using kill -0 [pid].

Hellmar Becker
  • 2,824
  • 12
  • 18
  • Your answer is correct only for the "*in general*" case, as you cannot do this safely, as there might very well be another process having been spawned with this very PID while the "original" process" ended. – alk Sep 29 '15 at 18:16