javascriptv8spidermonkeyasm.js

emscripten code for getpid and getppid functions


My aim to to find out the thread ids and process ids of the thread and the process that are running my javascript code. I could find no functions that could provide me this so I use the basic C code as written below and transpile it using emscripten to a JS code. The C code is as shown below :-

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

int main(){

    printf("I am %x and process %d called by %d\n", pthread_self(), getpid(), getppid());
    return 0;
}

The code transpiles without an error but I get the same result for the javascript at any browser I run, the result being I am 8 and process 42 called by 1. Can anyone please tell me why is this happening ?


Solution

  • At least in the browser, thread and process ID are not exposed to JavaScript, so there is no way to retrieve them. Apparently emscripten fills in some mock implementation that essentially just does "return 42;" because 42 is a nice number.

    It's not a question of programming language -- native binaries (compiled from C or other languages) can access such system internals, but anything running inside the browser's JavaScript VM cannot. It doesn't matter whether you write the JavaScript code by hand, or compile it from C (or Dart or Typescript or whatever).

    Of course, one can make external information available to programs running inside a VM, just like e.g. Date.now() retrieves the current time from the operating system and passes the value into JavaScript land. If you wanted to get getpid()/getppid() equivalents into browsers, you would have to go through the web standardization process. If you're more interested in node.js (or if you're implementing your own V8 embedding application), you could develop a native addon that provides such information.