0

Currently, I have one file calling another, and as an argument it passes over a pid converted into a string. Then, in a signal handler, I need to send a signal to the process given by the pid.

So I have:

//initialized as a global variable
pid_t* distantPid;

//in my main function
distantPid = &argv[1];

//then, in my signal handler
kill(*distantPid, WARNING_SIGNAL);

Whenever I try to compile this, though, I get an error saying 'Assignment from incompatible pointer type [assigned by default]'

I can't simply use argv[1] in the signal handler, because it's not in the main function.

Where am I going wrong?

Torin
  • 1

2 Answers2

2

You need to convert from a string to an integer. Try something like

//initialized as a global variable
pid_t distant_pid;

//in my main function
long long int pid_ll = strtoll(argv[1], NULL, 0);
distant_pid = (pid_t) pid_ll;

//then, in my signal handler
kill(distantPid, WARNING_SIGNAL);

If this is production code you'll want to make sure strtoll() was successful; I'll leave that as an exercise for you… see the man page for info about how.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
nemequ
  • 16,623
  • 1
  • 43
  • 62
  • Why use `atoi()`? Certainly `pid_t` is not defined to be only as wide as `int`? OTOH, it tends to be so: https://stackoverflow.com/q/1922761/2410359 – chux - Reinstate Monica Feb 07 '18 at 05:04
  • I think it's a un unsigned int, but fair point. The OS will actually handle the value wrapping around, and IIRC there is even a way to randomize the assigned PIDs (may require a kernel patch, not sure). Anyways, yeah `strtoull` would probably be a good idea, I'll edit the code. – nemequ Feb 07 '18 at 05:09
  • 1
    Perhaps signed: [Ref](http://www.gnu.org/software/libc/manual/html_node/Process-Identification.html) – chux - Reinstate Monica Feb 07 '18 at 05:13
  • 1
    Ah, you're right (POSIX: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/types.h.html). I honestly had no idea PIDs could be negative, thanks! I'll make another edit :) – nemequ Feb 07 '18 at 05:15
  • Yes the whole "what is the right `strto*`" to use is a bit tricky with types like `pid_t`, etc. One idea to convert the string with widest `strtoll()` or `strtoimax()` and then narrow - handling overflow in some TBD fashion. Another is to compare sizes or MAX value and then call the "right" `strto*`. I'd say this answer is good enough for the majority of cases. – chux - Reinstate Monica Feb 07 '18 at 05:26
  • You'll probably want to note whether the signal is sent successfully or not, and report if it isn't. That means checking the result of `kill()`. – Jonathan Leffler Feb 07 '18 at 05:28
0

convert string to int and pass it to kill command : kill(atoi(argv[1]), WARNING_SIGNAL);