Home:ALL Converter>Unix command line arguments to kill process after a single print

Unix command line arguments to kill process after a single print

Ask Time:2019-07-11T16:19:21         Author:yalaa

Json Formatter

I need to pass unix arguments to run C file so that it prints a certain line "Hello World" a single time only. The file uses fork to print the sentence multiple times but I need to send a kill signal to kill the processes after the sentence "Hello World" is printed once only.

I tried

./"file name" sleep 4 KILL -9 

I do not think I am using the right syntax here.

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>

int main(int argc, char * argv[])
{
   int m, i, c = 0;
   pid_t pgid;

   m = atoi(argv[1]);

   for(i = 0; i < 3; ++i)
{
   if(fork() > 0)
   {
       c = 1;
   }
}

if(!c)
{
    pgid = getpgid(getpid());
    setpgid(getpid(), getpid());
    kill(m * pgid, SIGINT);
}

sleep(3);

if(fork() > 0)
{
    puts("Hello World");
}

return 0;
}

It is printing few times and then it hangs.

Author:yalaa,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56984648/unix-command-line-arguments-to-kill-process-after-a-single-print
yy