0

Can we take thread id of pthread as input from the user? Is this the right way?

  int main(int argc, pthread_t id, char *argv[])

Or taking the input in a void pointer and then casting it to a long unsigned int? None of this is giving the correct answer. Is there a way that we can do this?

sol
  • 95
  • 1
  • 12

2 Answers2

0

No. The C standard specifies two signatures for main:

int main(void);
int main(int argc, char *argv[]);

Read this for more - What are the valid signatures for C's main() function?. You can pass the id of a pthread as a command line argument to main and then read it in argv. argv receives the executable name as the first argument (./program_name as below) and then other arguments as supplied. All arguments (delimited by space) are converted to strings literals. Execute your program as

./program_name 123454 

Inside main, you would do:

// in main

if(argc > 1) {
    pthread_t id = strtol(argv[1], NULL, 10)  // converts string to decimal int
    if(id == 0) {
        // either no integer was entered in base 10, or 0 was entered
        // handle it
    }
    // do stuff with id
}   

Please note that POSIX does not require pthred_t to be of integer type. It can even be defined as a structure. You will need to look into your sys/types.h header file and see how pthread_t is implemented. Then you can print or process it depending on how you see fit.

Include the header file stdlib.h for the prototype of strtol library function. As the name suggests, it converts a string to long int type of given base. Fore more on strtol, read this - man strtol.

Community
  • 1
  • 1
ajay
  • 9,402
  • 8
  • 44
  • 71
0

main has only two valid prototypes:

int main(void);
int main(int, char**);

If you wish to pass any arguments to main then you have to pass them as strings in the argument vector argv.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75