-1

i want save the current process id on a variable.

So, i do this:

double id = 0; //Global variable

.....

id = getpid();

printf("%d %d", id, getpid()); // the result ins't the same...

Well, i expected save the current process id on a global variable.

Edit:

new_pid = fork();
//new_pid2 = fork();
switch(new_pid) {
case -1:
        perror("fork failed");
        exit(1);
case 0:
        kill(getppid(), SIGUSR1);
        signal(SIGUSR1, trata_SIGSEGV);
        break;
default:
        signal(SIGUSR1, trata_SIGSEGV);
        kill(new_pid, SIGUSR1);
        break;
}
break;
  • Why is your variable id a double ? The variable returned by getpid is an int like. – mmeisson Jan 09 '19 at 23:28
  • 1
    What is the problem with the code you added in the edit? A possible problem is that you might be sending the signal before the other process has called `signal()` to establish the handler. Try calling `signal()` before you fork. – Barmar Jan 10 '19 at 00:01

2 Answers2

1

The issue here is the use of printf. Your id variable is of type double, and you pass that to printf when it's expecting an int. This will completely break the result.

Replace

double id = 0;

with

long id;

to keep it as an integral type.

Also, replace

printf("%d %d", id, getpid());

with

printf("%ld %ld", id, (long) getpid());

to ensure that the expected type is being passed to printf.

Also, no need to initialize id to 0 since you unconditionally assign to it later.

Thomas Jager
  • 4,836
  • 2
  • 16
  • 30
1

The problem is that you're printing id with the wrong format. You should either use %f:

printf("%f %d", id, getpid());

Correct format specifier for double in printf

or cast it to int:

printf("%d %d", (int)id, getpid());

A better idea would be to use the correct type when declaring id:

pid_t id;

This is an integer type, rather than a floating point type.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Barmar
  • 741,623
  • 53
  • 500
  • 612